Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

acp-client.ts

238 lines7.0 KB

1import {
2 ClientSideConnection,
3 PROTOCOL_VERSION,
4 ndJsonStream,
5} from '@agentclientprotocol/sdk'
6import { spawnHandleToAcpTransport } from '../transport/stdio'
7import type {
8 Client,
9 McpServer,
10 RequestPermissionRequest,
11 RequestPermissionResponse,
12 SessionNotification,
13} from '@agentclientprotocol/sdk'
14import type {
15 AcpPermissionOutcome,
16 AcpPermissionRequest,
17 AcpSessionUpdate,
18 AcpStopReason,
19 AcpUsage,
20} from '../types/acp-types'
21import type { AcpJsonRpcStream, AcpSessionTransport } from '../transport/types'
22​
23/**
24 * Identifies this client to the agent in the ACP `initialize` handshake. The
25 * `version` is informational (sent in `clientInfo`); keep it loosely in step
26 * with the package version. `clientInfo` is currently optional in the protocol
27 * but will become required, so we always send it.
28 * ponytail: hardcoded — clientInfo is diagnostic; a stale patch version is harmless.
29 */
30const CLIENT_INFO = {
31 name: '@tanstack/ai-acp',
32 title: 'TanStack AI',
33 version: '0.1.0',
34} as const
35​
36export interface AcpSessionHandle {
37 sessionId: string
38 resumed: boolean
39 prompt: (
40 text: string,
41 ) => Promise<{ stopReason: AcpStopReason; usage?: AcpUsage }>
42 cancel: () => Promise<void>
43 dispose: () => Promise<void>
45​
46export interface StartAcpSessionOptions {
47 transport: AcpSessionTransport
48 cwd: string
49 authMethodId?: string
50 mcpServers?: Array<{
51 name: string
52 url: string
53 headers?: Array<{ name: string; value: string }>
54 }>
55 resumeSessionId?: string
56 onUpdate: (update: AcpSessionUpdate) => void
57 onPermissionRequest: (
58 request: AcpPermissionRequest,
59 ) => Promise<AcpPermissionOutcome> | AcpPermissionOutcome
60 /**
61 * Harness-specific JSON-RPC notifications (e.g. Grok `_x.ai/session_notification`).
62 * Return without throwing — unknown vendor extensions must not tear down the session.
63 */
64 onExtNotification?: (method: string, params: Record<string, unknown>) => void
66​
67function streamFromTransport(transport: AcpSessionTransport): {
68 stream: AcpJsonRpcStream
69 teardown: () => Promise<void>
70 exited: Promise<never> | undefined
71 stderrTail: () => string
72} {
73 if (transport.kind === 'stdio') {
74 const byteTransport = spawnHandleToAcpTransport(transport.process)
75 return {
76 stream: ndJsonStream(byteTransport.writable, byteTransport.readable),
77 teardown: () => byteTransport.kill(),
78 exited: byteTransport.exited,
79 stderrTail: byteTransport.stderrTail,
80 }
81 }
82​
83 return {
84 stream: transport.stream,
85 teardown: transport.dispose,
86 exited: undefined,
87 stderrTail: transport.stderrTail ?? (() => ''),
88 }
90​
91/**
92 * Drive an ACP harness over stdio or a pre-connected JSON-RPC stream.
93 */
94export async function startAcpSession(
95 options: StartAcpSessionOptions,
96): Promise<AcpSessionHandle> {
97 const { stream, teardown, exited, stderrTail } = streamFromTransport(
98 options.transport,
99 )
100​
101 let replaying = false
102​
103 const client: Client = {
104 requestPermission: async (
105 params: RequestPermissionRequest,
106 ): Promise<RequestPermissionResponse> => {
107 const outcome = await options.onPermissionRequest(params)
108 return { outcome }
109 },
110 sessionUpdate: (params: SessionNotification): Promise<void> => {
111 if (!replaying) {
112 options.onUpdate(params.update as AcpSessionUpdate)
113 }
114 return Promise.resolve()
115 },
116 extNotification: (method, params) => {
117 options.onExtNotification?.(method, params)
118 return Promise.resolve()
119 },
120 }
121​
122 const race = <T>(work: Promise<T>): Promise<T> =>
123 exited !== undefined ? Promise.race([work, exited]) : work
124​
125 try {
126 const connection = new ClientSideConnection(() => client, stream)
127​
128 const initResult = await race(
129 connection.initialize({
130 protocolVersion: PROTOCOL_VERSION,
131 clientInfo: CLIENT_INFO,
132 clientCapabilities: {
133 // The agent runs inside the sandbox with direct filesystem + shell
134 // access, so it never needs to delegate file/terminal I/O back to the
135 // client. We advertise these as unsupported; per the ACP spec the
136 // agent MUST then treat them as unavailable and not call them.
137 fs: { readTextFile: false, writeTextFile: false },
138 },
139 }),
140 )
141​
142 // Protocol-version negotiation: the agent echoes the version it will speak.
143 // The spec says a client SHOULD close the connection if that version is one
144 // it doesn't support. We only implement the current PROTOCOL_VERSION, so a
145 // higher number means the agent needs a newer client than this one.
146 if (
147 typeof initResult.protocolVersion === 'number' &&
148 initResult.protocolVersion > PROTOCOL_VERSION
149 ) {
150 throw new Error(
151 `ACP agent negotiated protocol version ${initResult.protocolVersion}, ` +
152 `but this client supports up to ${PROTOCOL_VERSION}. Update @tanstack/ai-acp.`,
153 )
154 }
155​
156 if (options.authMethodId !== undefined) {
157 const available = initResult.authMethods ?? []
158 if (!available.some((method) => method.id === options.authMethodId)) {
159 throw new Error(
160 `Harness does not advertise the ACP auth method '${options.authMethodId}'. Available: ${
161 available.map((method) => method.id).join(', ') || '(none)'
162 }.`,
163 )
164 }
165 await race(connection.authenticate({ methodId: options.authMethodId }))
166 }
167​
168 const mcpServers: Array<McpServer> = (options.mcpServers ?? []).map(
169 (server) => ({
170 type: 'http' as const,
171 name: server.name,
172 url: server.url,
173 headers: server.headers ?? [],
174 }),
175 )
176​
177 let sessionId: string | undefined
178 let resumed = false
179 if (
180 options.resumeSessionId !== undefined &&
181 initResult.agentCapabilities?.loadSession === true
182 ) {
183 replaying = true
184 try {
185 await race(
186 connection.loadSession({
187 sessionId: options.resumeSessionId,
188 cwd: options.cwd,
189 mcpServers,
190 }),
191 )
192 sessionId = options.resumeSessionId
193 resumed = true
194 } catch {
195 // Session unknown — fall through to a fresh one.
196 } finally {
197 replaying = false
198 }
199 }
200​
201 if (sessionId === undefined) {
202 const session = await race(
203 connection.newSession({ cwd: options.cwd, mcpServers }),
204 )
205 sessionId = session.sessionId
206 }
207​
208 return {
209 sessionId,
210 resumed,
211 prompt: async (text: string) => {
212 const response = await race(
213 connection.prompt({
214 sessionId,
215 prompt: [{ type: 'text', text }],
216 }),
217 )
218 return {
219 stopReason: response.stopReason,
220 ...(response.usage != null && { usage: response.usage }),
221 }
222 },
223 cancel: () => connection.cancel({ sessionId }),
224 dispose: teardown,
225 }
226 } catch (error) {
227 await teardown()
228 const tail = stderrTail().trim()
229 if (
230 error instanceof Error &&
231 tail !== '' &&
232 !error.message.includes(tail)
233 ) {
234 throw new Error(`${error.message}\nstderr: ${tail}`, { cause: error })
235 }
236 throw error
237 }