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

AcpSessionRuntime.ts

722 lines25.8 KB

1import { Cause, Deferred, Effect, Exit, Layer, Queue, Ref, Scope, Context, Stream } from "effect";
2import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
3import * as EffectAcpClient from "effect-acp/client";
4import * as EffectAcpErrors from "effect-acp/errors";
5import type * as EffectAcpSchema from "effect-acp/schema";
6import type * as EffectAcpProtocol from "effect-acp/protocol";
7​
8import {
9 collectSessionConfigOptionValues,
10 extractModelConfigId,
11 findSessionConfigOption,
12 mergeToolCallState,
13 parseSessionModeState,
14 parseSessionUpdateEvent,
15 type AcpParsedSessionEvent,
16 type AcpSessionModeState,
17 type AcpToolCallState,
18} from "./AcpRuntimeModel.ts";
19​
20export interface AcpSpawnInput {
21 readonly command: string;
22 readonly args: ReadonlyArray<string>;
23 readonly cwd?: string;
24 readonly env?: NodeJS.ProcessEnv;
26​
27export interface AcpSessionRuntimeOptions {
28 readonly spawn: AcpSpawnInput;
29 readonly cwd: string;
30 readonly resumeSessionId?: string;
31 readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"];
32 readonly clientInfo: {
33 readonly name: string;
34 readonly version: string;
35 };
36 readonly authMethodId: string;
37 readonly requestLogger?: (event: AcpSessionRequestLogEvent) => Effect.Effect<void, never>;
38 readonly protocolLogging?: {
39 readonly logIncoming?: boolean;
40 readonly logOutgoing?: boolean;
41 readonly logger?: (event: EffectAcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;
42 };
44​
45export interface AcpSessionRequestLogEvent {
46 readonly method: string;
47 readonly payload: unknown;
48 readonly status: "started" | "succeeded" | "failed";
49 readonly result?: unknown;
50 readonly cause?: Cause.Cause<EffectAcpErrors.AcpError>;
52​
53export interface AcpSessionRuntimeStartResult {
54 readonly sessionId: string;
55 readonly initializeResult: EffectAcpSchema.InitializeResponse;
56 readonly sessionSetupResult:
57 | EffectAcpSchema.LoadSessionResponse
58 | EffectAcpSchema.NewSessionResponse
59 | EffectAcpSchema.ResumeSessionResponse;
60 readonly modelConfigId: string | undefined;
62​
63export interface AcpSessionRuntimeShape {
64 readonly handleRequestPermission: EffectAcpClient.AcpClientShape["handleRequestPermission"];
65 readonly handleElicitation: EffectAcpClient.AcpClientShape["handleElicitation"];
66 readonly handleReadTextFile: EffectAcpClient.AcpClientShape["handleReadTextFile"];
67 readonly handleWriteTextFile: EffectAcpClient.AcpClientShape["handleWriteTextFile"];
68 readonly handleCreateTerminal: EffectAcpClient.AcpClientShape["handleCreateTerminal"];
69 readonly handleTerminalOutput: EffectAcpClient.AcpClientShape["handleTerminalOutput"];
70 readonly handleTerminalWaitForExit: EffectAcpClient.AcpClientShape["handleTerminalWaitForExit"];
71 readonly handleTerminalKill: EffectAcpClient.AcpClientShape["handleTerminalKill"];
72 readonly handleTerminalRelease: EffectAcpClient.AcpClientShape["handleTerminalRelease"];
73 readonly handleSessionUpdate: EffectAcpClient.AcpClientShape["handleSessionUpdate"];
74 readonly handleElicitationComplete: EffectAcpClient.AcpClientShape["handleElicitationComplete"];
75 readonly handleUnknownExtRequest: EffectAcpClient.AcpClientShape["handleUnknownExtRequest"];
76 readonly handleUnknownExtNotification: EffectAcpClient.AcpClientShape["handleUnknownExtNotification"];
77 readonly handleExtRequest: EffectAcpClient.AcpClientShape["handleExtRequest"];
78 readonly handleExtNotification: EffectAcpClient.AcpClientShape["handleExtNotification"];
79 readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
80 readonly getEvents: () => Stream.Stream<AcpParsedSessionEvent, never>;
81 readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
82 readonly getConfigOptions: Effect.Effect<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;
83 readonly prompt: (
84 payload: Omit<EffectAcpSchema.PromptRequest, "sessionId">,
85 ) => Effect.Effect<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>;
86 readonly cancel: Effect.Effect<void, EffectAcpErrors.AcpError>;
87 readonly setMode: (
88 modeId: string,
89 ) => Effect.Effect<EffectAcpSchema.SetSessionModeResponse, EffectAcpErrors.AcpError>;
90 readonly setConfigOption: (
91 configId: string,
92 value: string | boolean,
93 ) => Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError>;
94 readonly setModel: (model: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;
95 readonly request: (
96 method: string,
97 payload: unknown,
98 ) => Effect.Effect<unknown, EffectAcpErrors.AcpError>;
99 readonly notify: (
100 method: string,
101 payload: unknown,
102 ) => Effect.Effect<void, EffectAcpErrors.AcpError>;
104​
105interface AcpStartedState extends AcpSessionRuntimeStartResult {}
106​
107type AcpStartState =
108 | { readonly _tag: "NotStarted" }
109 | {
110 readonly _tag: "Starting";
111 readonly deferred: Deferred.Deferred<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
112 }
113 | { readonly _tag: "Started"; readonly result: AcpStartedState };
114​
115interface AcpAssistantSegmentState {
116 readonly nextSegmentIndex: number;
117 readonly activeItemId?: string;
119​
120interface EnsureActiveAssistantSegmentResult {
121 readonly itemId: string;
122 readonly startedEvent?: Extract<AcpParsedSessionEvent, { readonly _tag: "AssistantItemStarted" }>;
124​
125export class AcpSessionRuntime extends Context.Service<AcpSessionRuntime, AcpSessionRuntimeShape>()(
126 "t3/provider/acp/AcpSessionRuntime",
127) {
128 static layer(
129 options: AcpSessionRuntimeOptions,
130 ): Layer.Layer<
131 AcpSessionRuntime,
132 EffectAcpErrors.AcpError,
133 ChildProcessSpawner.ChildProcessSpawner
134 > {
135 return Layer.effect(AcpSessionRuntime, makeAcpSessionRuntime(options));
136 }
138​
139const makeAcpSessionRuntime = (
140 options: AcpSessionRuntimeOptions,
141): Effect.Effect<
142 AcpSessionRuntimeShape,
143 EffectAcpErrors.AcpError,
144 ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
145> =>
146 Effect.gen(function* () {
147 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
148 const runtimeScope = yield* Scope.Scope;
149 const eventQueue = yield* Queue.unbounded<AcpParsedSessionEvent>();
150 const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
151 const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallState>());
152 const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });
153 const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));
154 const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });
155​
156 const logRequest = (event: AcpSessionRequestLogEvent) =>
157 options.requestLogger ? options.requestLogger(event) : Effect.void;
158​
159 const runLoggedRequest = <A>(
160 method: string,
161 payload: unknown,
162 effect: Effect.Effect<A, EffectAcpErrors.AcpError>,
163 ): Effect.Effect<A, EffectAcpErrors.AcpError> =>
164 logRequest({ method, payload, status: "started" }).pipe(
165 Effect.flatMap(() =>
166 effect.pipe(
167 Effect.tap((result) =>
168 logRequest({
169 method,
170 payload,
171 status: "succeeded",
172 result,
173 }),
174 ),
175 Effect.onError((cause) =>
176 logRequest({
177 method,
178 payload,
179 status: "failed",
180 cause,
181 }),
182 ),
183 ),
184 ),
185 );
186​
187 const child = yield* spawner
188 .spawn(
189 ChildProcess.make(options.spawn.command, [...options.spawn.args], {
190 ...(options.spawn.cwd ? { cwd: options.spawn.cwd } : {}),
191 ...(options.spawn.env ? { env: { ...process.env, ...options.spawn.env } } : {}),
192 shell: process.platform === "win32",
193 }),
194 )
195 .pipe(
196 Effect.provideService(Scope.Scope, runtimeScope),
197 Effect.mapError(
198 (cause) =>
199 new EffectAcpErrors.AcpSpawnError({
200 command: options.spawn.command,
201 cause,
202 }),
203 ),
204 );
205​
206 const acpContext = yield* Layer.build(
207 EffectAcpClient.layerChildProcess(child, {
208 ...(options.protocolLogging?.logIncoming !== undefined
209 ? { logIncoming: options.protocolLogging.logIncoming }
210 : {}),
211 ...(options.protocolLogging?.logOutgoing !== undefined
212 ? { logOutgoing: options.protocolLogging.logOutgoing }
213 : {}),
214 ...(options.protocolLogging?.logger ? { logger: options.protocolLogging.logger } : {}),
215 }),
216 ).pipe(Effect.provideService(Scope.Scope, runtimeScope));
217​
218 const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext));
219​
220 yield* acp.handleSessionUpdate((notification) =>
221 handleSessionUpdate({
222 queue: eventQueue,
223 modeStateRef,
224 toolCallsRef,
225 assistantSegmentRef,
226 params: notification,
227 }),
228 );
229​
230 const initializeClientCapabilities = {
231 fs: {
232 readTextFile: false,
233 writeTextFile: false,
234 ...options.clientCapabilities?.fs,
235 },
236 terminal: options.clientCapabilities?.terminal ?? false,
237 ...(options.clientCapabilities?.auth ? { auth: options.clientCapabilities.auth } : {}),
238 ...(options.clientCapabilities?.elicitation
239 ? { elicitation: options.clientCapabilities.elicitation }
240 : {}),
241 ...(options.clientCapabilities?._meta ? { _meta: options.clientCapabilities._meta } : {}),
242 } satisfies NonNullable<EffectAcpSchema.InitializeRequest["clientCapabilities"]>;
243​
244 const getStartedState = Effect.gen(function* () {
245 const state = yield* Ref.get(startStateRef);
246 if (state._tag === "Started") {
247 return state.result;
248 }
249 return yield* new EffectAcpErrors.AcpTransportError({
250 detail: "ACP session runtime has not been started",
251 cause: new Error("ACP session runtime has not been started"),
252 });
253 });
254​
255 const validateConfigOptionValue = (
256 configId: string,
257 value: string | boolean,
258 ): Effect.Effect<void, EffectAcpErrors.AcpError> =>
259 Effect.gen(function* () {
260 const configOption = findSessionConfigOption(yield* Ref.get(configOptionsRef), configId);
261 if (!configOption) {
262 return;
263 }
264 if (configOption.type === "boolean") {
265 if (typeof value === "boolean") {
266 return;
267 }
268 return yield* new EffectAcpErrors.AcpRequestError({
269 code: -32602,
270 errorMessage: `Invalid value ${JSON.stringify(value)} for session config option "${configOption.id}": expected boolean`,
271 data: {
272 configId: configOption.id,
273 expectedType: "boolean",
274 receivedValue: value,
275 },
276 });
277 }
278 if (typeof value !== "string") {
279 return yield* new EffectAcpErrors.AcpRequestError({
280 code: -32602,
281 errorMessage: `Invalid value ${JSON.stringify(value)} for session config option "${configOption.id}": expected string`,
282 data: {
283 configId: configOption.id,
284 expectedType: "string",
285 receivedValue: value,
286 },
287 });
288 }
289 const allowedValues = collectSessionConfigOptionValues(configOption);
290 if (allowedValues.includes(value)) {
291 return;
292 }
293 return yield* new EffectAcpErrors.AcpRequestError({
294 code: -32602,
295 errorMessage: `Invalid value ${JSON.stringify(value)} for session config option "${configOption.id}": expected one of ${allowedValues.join(", ")}`,
296 data: {
297 configId: configOption.id,
298 allowedValues,
299 receivedValue: value,
300 },
301 });
302 });
303​
304 const updateConfigOptions = (
305 response:
306 | EffectAcpSchema.SetSessionConfigOptionResponse
307 | EffectAcpSchema.LoadSessionResponse
308 | EffectAcpSchema.NewSessionResponse
309 | EffectAcpSchema.ResumeSessionResponse,
310 ): Effect.Effect<void> => Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(response));
311​
312 const updateCurrentModeId = (modeId: string): Effect.Effect<void> =>
313 Ref.update(modeStateRef, (current) =>
314 current ? { ...current, currentModeId: modeId } : current,
315 );
316​
317 const setConfigOption = (
318 configId: string,
319 value: string | boolean,
320 ): Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError> =>
321 validateConfigOptionValue(configId, value).pipe(
322 Effect.flatMap(() => getStartedState),
323 Effect.flatMap((started) =>
324 Ref.get(configOptionsRef).pipe(
325 Effect.flatMap((configOptions) => {
326 const existing = findSessionConfigOption(configOptions, configId);
327 if (existing && configOptionCurrentValueMatches(existing, value)) {
328 return Effect.succeed({
329 configOptions,
330 } satisfies EffectAcpSchema.SetSessionConfigOptionResponse);
331 }
332 const requestPayload =
333 typeof value === "boolean"
334 ? ({
335 sessionId: started.sessionId,
336 configId,
337 type: "boolean",
338 value,
339 } satisfies EffectAcpSchema.SetSessionConfigOptionRequest)
340 : ({
341 sessionId: started.sessionId,
342 configId,
343 value: String(value),
344 } satisfies EffectAcpSchema.SetSessionConfigOptionRequest);
345 return runLoggedRequest(
346 "session/set_config_option",
347 requestPayload,
348 acp.agent.setSessionConfigOption(requestPayload),
349 ).pipe(Effect.tap((response) => updateConfigOptions(response)));
350 }),
351 ),
352 ),
353 );
354​
355 const startOnce = Effect.gen(function* () {
356 const initializePayload = {
357 protocolVersion: 1,
358 clientCapabilities: initializeClientCapabilities,
359 clientInfo: options.clientInfo,
360 } satisfies EffectAcpSchema.InitializeRequest;
361​
362 const initializeResult = yield* runLoggedRequest(
363 "initialize",
364 initializePayload,
365 acp.agent.initialize(initializePayload),
366 );
367​
368 const authenticatePayload = {
369 methodId: options.authMethodId,
370 } satisfies EffectAcpSchema.AuthenticateRequest;
371​
372 yield* runLoggedRequest(
373 "authenticate",
374 authenticatePayload,
375 acp.agent.authenticate(authenticatePayload),
376 );
377​
378 let sessionId: string;
379 let sessionSetupResult:
380 | EffectAcpSchema.LoadSessionResponse
381 | EffectAcpSchema.NewSessionResponse
382 | EffectAcpSchema.ResumeSessionResponse;
383 if (options.resumeSessionId) {
384 const loadPayload = {
385 sessionId: options.resumeSessionId,
386 cwd: options.cwd,
387 mcpServers: [],
388 } satisfies EffectAcpSchema.LoadSessionRequest;
389 const resumed = yield* runLoggedRequest(
390 "session/load",
391 loadPayload,
392 acp.agent.loadSession(loadPayload),
393 ).pipe(Effect.exit);
394 if (Exit.isSuccess(resumed)) {
395 sessionId = options.resumeSessionId;
396 sessionSetupResult = resumed.value;
397 } else {
398 const createPayload = {
399 cwd: options.cwd,
400 mcpServers: [],
401 } satisfies EffectAcpSchema.NewSessionRequest;
402 const created = yield* runLoggedRequest(
403 "session/new",
404 createPayload,
405 acp.agent.createSession(createPayload),
406 );
407 sessionId = created.sessionId;
408 sessionSetupResult = created;
409 }
410 } else {
411 const createPayload = {
412 cwd: options.cwd,
413 mcpServers: [],
414 } satisfies EffectAcpSchema.NewSessionRequest;
415 const created = yield* runLoggedRequest(
416 "session/new",
417 createPayload,
418 acp.agent.createSession(createPayload),
419 );
420 sessionId = created.sessionId;
421 sessionSetupResult = created;
422 }
423​
424 yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));
425 yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));
426​
427 const nextState = {
428 sessionId,
429 initializeResult,
430 sessionSetupResult,
431 modelConfigId: extractModelConfigId(sessionSetupResult),
432 } satisfies AcpStartedState;
433 return nextState;
434 });
435​
436 const start = Effect.gen(function* () {
437 const deferred = yield* Deferred.make<
438 AcpSessionRuntimeStartResult,
439 EffectAcpErrors.AcpError
440 >();
441 const effect = yield* Ref.modify(startStateRef, (state) => {
442 switch (state._tag) {
443 case "Started":
444 return [Effect.succeed(state.result), state] as const;
445 case "Starting":
446 return [Deferred.await(state.deferred), state] as const;
447 case "NotStarted":
448 return [
449 startOnce.pipe(
450 Effect.tap((result) =>
451 Ref.set(startStateRef, { _tag: "Started", result }).pipe(
452 Effect.andThen(Deferred.succeed(deferred, result)),
453 ),
454 ),
455 Effect.onError((cause) =>
456 Deferred.failCause(deferred, cause).pipe(
457 Effect.andThen(Ref.set(startStateRef, { _tag: "NotStarted" })),
458 ),
459 ),
460 ),
461 { _tag: "Starting", deferred } satisfies AcpStartState,
462 ] as const;
463 }
464 });
465 return yield* effect;
466 });
467​
468 return {
469 handleRequestPermission: acp.handleRequestPermission,
470 handleElicitation: acp.handleElicitation,
471 handleReadTextFile: acp.handleReadTextFile,
472 handleWriteTextFile: acp.handleWriteTextFile,
473 handleCreateTerminal: acp.handleCreateTerminal,
474 handleTerminalOutput: acp.handleTerminalOutput,
475 handleTerminalWaitForExit: acp.handleTerminalWaitForExit,
476 handleTerminalKill: acp.handleTerminalKill,
477 handleTerminalRelease: acp.handleTerminalRelease,
478 handleSessionUpdate: acp.handleSessionUpdate,
479 handleElicitationComplete: acp.handleElicitationComplete,
480 handleUnknownExtRequest: acp.handleUnknownExtRequest,
481 handleUnknownExtNotification: acp.handleUnknownExtNotification,
482 handleExtRequest: acp.handleExtRequest,
483 handleExtNotification: acp.handleExtNotification,
484 start: () => start,
485 getEvents: () => Stream.fromQueue(eventQueue),
486 getModeState: Ref.get(modeStateRef),
487 getConfigOptions: Ref.get(configOptionsRef),
488 prompt: (payload) =>
489 getStartedState.pipe(
490 Effect.flatMap((started) => {
491 const requestPayload = {
492 sessionId: started.sessionId,
493 ...payload,
494 } satisfies EffectAcpSchema.PromptRequest;
495 return closeActiveAssistantSegment({
496 queue: eventQueue,
497 assistantSegmentRef,
498 }).pipe(
499 Effect.andThen(
500 runLoggedRequest(
501 "session/prompt",
502 requestPayload,
503 acp.agent.prompt(requestPayload),
504 ),
505 ),
506 Effect.tap(() =>
507 closeActiveAssistantSegment({
508 queue: eventQueue,
509 assistantSegmentRef,
510 }),
511 ),
512 );
513 }),
514 ),
515 cancel: getStartedState.pipe(
516 Effect.flatMap((started) => acp.agent.cancel({ sessionId: started.sessionId })),
517 ),
518 setMode: (modeId) =>
519 Ref.get(modeStateRef).pipe(
520 Effect.flatMap((modeState) => {
521 if (modeState?.currentModeId === modeId) {
522 return Effect.succeed({} satisfies EffectAcpSchema.SetSessionModeResponse);
523 }
524 return setConfigOption("mode", modeId).pipe(
525 Effect.tap(() => updateCurrentModeId(modeId)),
526 Effect.as({} satisfies EffectAcpSchema.SetSessionModeResponse),
527 );
528 }),
529 ),
530 setConfigOption,
531 setModel: (model) =>
532 getStartedState.pipe(
533 Effect.flatMap((started) => setConfigOption(started.modelConfigId ?? "model", model)),
534 Effect.asVoid,
535 ),
536 request: (method, payload) =>
537 runLoggedRequest(method, payload, acp.raw.request(method, payload)),
538 notify: acp.raw.notify,
539 } satisfies AcpSessionRuntimeShape;
540 });
541​
542function sessionConfigOptionsFromSetup(
543 response:
544 | {
545 readonly configOptions?: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null;
546 }
547 | undefined,
548): ReadonlyArray<EffectAcpSchema.SessionConfigOption> {
549 return response?.configOptions ?? [];
551​
552function configOptionCurrentValueMatches(
553 configOption: EffectAcpSchema.SessionConfigOption,
554 value: string | boolean,
555): boolean {
556 const currentValue = configOption.currentValue;
557 if (configOption.type === "boolean") {
558 return currentValue === value;
559 }
560 if (typeof currentValue !== "string") {
561 return false;
562 }
563 return currentValue.trim() === String(value).trim();
565​
566const handleSessionUpdate = ({
567 queue,
568 modeStateRef,
569 toolCallsRef,
570 assistantSegmentRef,
571 params,
572}: {
573 readonly queue: Queue.Queue<AcpParsedSessionEvent>;
574 readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
575 readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallState>>;
576 readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
577 readonly params: EffectAcpSchema.SessionNotification;
578}): Effect.Effect<void> =>
579 Effect.gen(function* () {
580 const parsed = parseSessionUpdateEvent(params);
581 if (parsed.modeId) {
582 yield* Ref.update(modeStateRef, (current) =>
583 current === undefined ? current : updateModeState(current, parsed.modeId!),
584 );
585 }
586 for (const event of parsed.events) {
587 if (event._tag === "ToolCallUpdated") {
588 yield* closeActiveAssistantSegment({
589 queue,
590 assistantSegmentRef,
591 });
592 const { previous, merged } = yield* Ref.modify(toolCallsRef, (current) => {
593 const previous = current.get(event.toolCall.toolCallId);
594 const nextToolCall = mergeToolCallState(previous, event.toolCall);
595 const next = new Map(current);
596 if (nextToolCall.status === "completed" || nextToolCall.status === "failed") {
597 next.delete(nextToolCall.toolCallId);
598 } else {
599 next.set(nextToolCall.toolCallId, nextToolCall);
600 }
601 return [{ previous, merged: nextToolCall }, next] as const;
602 });
603 if (!shouldEmitToolCallUpdate(previous, merged)) {
604 continue;
605 }
606 yield* Queue.offer(queue, {
607 _tag: "ToolCallUpdated",
608 toolCall: merged,
609 rawPayload: event.rawPayload,
610 });
611 continue;
612 }
613 if (event._tag === "ContentDelta") {
614 if (event.text.trim().length === 0) {
615 const assistantSegmentState = yield* Ref.get(assistantSegmentRef);
616 if (!assistantSegmentState.activeItemId) {
617 continue;
618 }
619 }
620 const itemId = yield* ensureActiveAssistantSegment({
621 queue,
622 assistantSegmentRef,
623 sessionId: params.sessionId,
624 });
625 yield* Queue.offer(queue, {
626 ...event,
627 itemId,
628 });
629 continue;
630 }
631 yield* Queue.offer(queue, event);
632 }
633 });
634​
635function updateModeState(modeState: AcpSessionModeState, nextModeId: string): AcpSessionModeState {
636 const normalized = nextModeId.trim();
637 if (!normalized) {
638 return modeState;
639 }
640 return modeState.availableModes.some((mode) => mode.id === normalized)
641 ? {
642 ...modeState,
643 currentModeId: normalized,
644 }
645 : modeState;
647​
648function shouldEmitToolCallUpdate(
649 previous: AcpToolCallState | undefined,
650 next: AcpToolCallState,
651): boolean {
652 if (next.status === "completed" || next.status === "failed") {
653 return true;
654 }
655 if (!next.detail) {
656 return false;
657 }
658 return previous === undefined || previous.title !== next.title || previous.detail !== next.detail;
660​
661const assistantItemId = (sessionId: string, segmentIndex: number) =>
662 `assistant:${sessionId}:segment:${segmentIndex}`;
663​
664const ensureActiveAssistantSegment = ({
665 queue,
666 assistantSegmentRef,
667 sessionId,
668}: {
669 readonly queue: Queue.Queue<AcpParsedSessionEvent>;
670 readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
671 readonly sessionId: string;
672}) =>
673 Ref.modify<AcpAssistantSegmentState, EnsureActiveAssistantSegmentResult>(
674 assistantSegmentRef,
675 (current) => {
676 if (current.activeItemId) {
677 return [{ itemId: current.activeItemId }, current] as const;
678 }
679 const itemId = assistantItemId(sessionId, current.nextSegmentIndex);
680 return [
681 {
682 itemId,
683 startedEvent: {
684 _tag: "AssistantItemStarted",
685 itemId,
686 } satisfies Extract<AcpParsedSessionEvent, { readonly _tag: "AssistantItemStarted" }>,
687 },
688 {
689 nextSegmentIndex: current.nextSegmentIndex + 1,
690 activeItemId: itemId,
691 } satisfies AcpAssistantSegmentState,
692 ] as const;
693 },
694 ).pipe(
695 Effect.flatMap((result) =>
696 result.startedEvent
697 ? Queue.offer(queue, result.startedEvent).pipe(Effect.as(result.itemId))
698 : Effect.succeed(result.itemId),
699 ),
700 );
701​
702const closeActiveAssistantSegment = ({
703 queue,
704 assistantSegmentRef,
705}: {
706 readonly queue: Queue.Queue<AcpParsedSessionEvent>;
707 readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
708}) =>
709 Ref.modify(assistantSegmentRef, (current) => {
710 if (!current.activeItemId) {
711 return [undefined, current] as const;
712 }
713 return [
714 {
715 _tag: "AssistantItemCompleted",
716 itemId: current.activeItemId,
717 } satisfies AcpParsedSessionEvent,
718 {
719 nextSegmentIndex: current.nextSegmentIndex,
720 } satisfies AcpAssistantSegmentState,
721 ] as const;
722 }).pipe(Effect.flatMap((event) => (event ? Queue.offer(queue, event) : Effect.void)));