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

AcpRuntimeModel.ts

613 lines17.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.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;
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);
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 );
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 };
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 }
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 }
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;
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;
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);
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;
288​
289function normalizeToolKind(kind: unknown): string | undefined {
290 return typeof kind === "string" && kind.trim().length > 0 ? kind.trim() : undefined;
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 }
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 };
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 );
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 };
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 };
456​
457export function sessionUpdateIsReplay(params: EffectAcpSchema.SessionNotification): boolean {
458 const meta = params._meta;
459 return isRecord(meta) && meta.isReplay === true;
461​
462/** Replay chunks and substantive updates during session/load; not Grok keepalives. */
463export function sessionUpdateCountsAsLoadReplayActivity(
464 params: EffectAcpSchema.SessionNotification,
465 gatedSessionId?: string,
466): boolean {
467 if (gatedSessionId !== undefined && params.sessionId !== gatedSessionId) {
468 return false;
469 }
470 if (sessionUpdateIsReplay(params)) return true;
471 const update = params.update;
472 switch (update.sessionUpdate) {
473 case "agent_message_chunk":
474 case "agent_thought_chunk":
475 return update.content.type === "text" && update.content.text.length > 0;
476 case "tool_call":
477 case "tool_call_update":
478 case "plan":
479 case "available_commands_update":
480 case "current_mode_update":
481 case "config_option_update":
482 case "session_info_update":
483 case "usage_update":
484 return true;
485 default:
486 return false;
487 }
489​
490export interface SessionLoadGate {
491 readonly active: boolean;
492 /** Only notifications for this session refresh load-replay idle activity. */
493 readonly sessionId: string;
494 readonly lastActivityAtMillis: number | undefined;
495 readonly idleGap: Duration.Duration;
496 readonly initializeResult: EffectAcpSchema.InitializeResponse;
498​
499export const waitForSessionLoadReplayIdle = (input: {
500 readonly gateRef: Ref.Ref<Option.Option<SessionLoadGate>>;
501}): Effect.Effect<EffectAcpSchema.LoadSessionResponse, never> =>
502 Effect.gen(function* () {
503 const pollInterval = Duration.millis(25);
504 while (true) {
505 const gate = yield* Ref.get(input.gateRef);
506 if (
507 Option.isSome(gate) &&
508 gate.value.active &&
509 gate.value.lastActivityAtMillis !== undefined
510 ) {
511 const idleGapMillis = Duration.toMillis(gate.value.idleGap);
512 const nowMillis = yield* Clock.currentTimeMillis;
513 if (nowMillis - gate.value.lastActivityAtMillis >= idleGapMillis) {
514 return syntheticLoadSessionResponseFromInitialize(gate.value.initializeResult);
515 }
516 }
517 yield* Effect.sleep(pollInterval);
518 }
519 });
520​
521export function syntheticLoadSessionResponseFromInitialize(
522 initializeResult: EffectAcpSchema.InitializeResponse,
523): EffectAcpSchema.LoadSessionResponse {
524 const meta = initializeResult._meta;
525 const modelState = isRecord(meta) ? meta.modelState : undefined;
526 const modeState = isRecord(meta) ? meta.modeState : undefined;
527 const models = isSessionModelState(modelState) ? modelState : undefined;
528 const modes = isSessionModeState(modeState) ? modeState : undefined;
529​
530 return {
531 ...(models ? { models } : {}),
532 ...(modes ? { modes } : {}),
533 _meta: {
534 t3SessionLoadReady: "replay_idle",
535 },
536 };
538​
539export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotification): {
540 readonly modeId?: string;
541 readonly events: ReadonlyArray<AcpParsedSessionEvent>;
542} {
543 const upd = params.update;
544 const events: Array<AcpParsedSessionEvent> = [];
545 let modeId: string | undefined;
546​
547 switch (upd.sessionUpdate) {
548 case "current_mode_update": {
549 modeId = upd.currentModeId.trim();
550 if (modeId) {
551 events.push({
552 _tag: "ModeChanged",
553 modeId,
554 });
555 }
556 break;
557 }
558 case "plan": {
559 const plan = upd.entries.map((entry, index) => ({
560 step: entry.content.trim().length > 0 ? entry.content.trim() : `Step ${index + 1}`,
561 status: normalizePlanStepStatus(entry.status),
562 }));
563 if (plan.length > 0) {
564 events.push({
565 _tag: "PlanUpdated",
566 payload: {
567 plan,
568 },
569 rawPayload: params,
570 });
571 }
572 break;
573 }
574 case "tool_call": {
575 const toolCall = parseTypedToolCallState(upd, {
576 fallbackStatus: "pending",
577 });
578 if (toolCall) {
579 events.push({
580 _tag: "ToolCallUpdated",
581 toolCall,
582 rawPayload: params,
583 });
584 }
585 break;
586 }
587 case "tool_call_update": {
588 const toolCall = parseTypedToolCallState(upd);
589 if (toolCall) {
590 events.push({
591 _tag: "ToolCallUpdated",
592 toolCall,
593 rawPayload: params,
594 });
595 }
596 break;
597 }
598 case "agent_message_chunk": {
599 if (upd.content.type === "text" && upd.content.text.length > 0) {
600 events.push({
601 _tag: "ContentDelta",
602 text: upd.content.text,
603 rawPayload: params,
604 });
605 }
606 break;
607 }
608 default:
609 break;
610 }
611​
612 return { ...(modeId !== undefined ? { modeId } : {}), events };