@qlairoslabs/acp-client 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +222 -0
- package/package.json +62 -0
- package/src/adapters.ts +52 -0
- package/src/agent-client.ts +50 -0
- package/src/agent-session.ts +212 -0
- package/src/capabilities.ts +104 -0
- package/src/cli/index.ts +112 -0
- package/src/client.ts +613 -0
- package/src/config-options.ts +65 -0
- package/src/controller.ts +446 -0
- package/src/degraded/emulator.ts +77 -0
- package/src/degraded/extract.ts +87 -0
- package/src/degraded/index.ts +18 -0
- package/src/degraded/pty-client.ts +304 -0
- package/src/degraded/pty-transport.ts +130 -0
- package/src/errors.ts +28 -0
- package/src/index.ts +81 -0
- package/src/logger.ts +65 -0
- package/src/parser/index.ts +4 -0
- package/src/parser/ollama.ts +26 -0
- package/src/parser/types.ts +20 -0
- package/src/repl/colors.ts +15 -0
- package/src/repl/commands.ts +435 -0
- package/src/repl/index.ts +9 -0
- package/src/repl/repl.ts +312 -0
- package/src/session-manager.ts +125 -0
- package/src/session-store.ts +96 -0
- package/src/transport/acp-transport.ts +193 -0
- package/src/types.ts +112 -0
- package/src/updates.ts +45 -0
package/src/client.ts
ADDED
|
@@ -0,0 +1,613 @@
|
|
|
1
|
+
// AcpClient — the core deliverable. Implements the AgentClient output contract and
|
|
2
|
+
// adds the rich ACP input surface (capabilities, configOptions, sessions, auth).
|
|
3
|
+
//
|
|
4
|
+
// Lifecycle (SPEC.md): construct (sync, no spawn) → connect() (spawn + initialize +
|
|
5
|
+
// session/new|load) → prompt(). Capabilities and configOptions are populated by
|
|
6
|
+
// connect() so callers can inspect them BEFORE prompting.
|
|
7
|
+
|
|
8
|
+
import { PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
|
|
9
|
+
import type * as schema from "@agentclientprotocol/sdk";
|
|
10
|
+
import type { Adapter } from "./adapters.ts";
|
|
11
|
+
import { buildSpawnCommand } from "./adapters.ts";
|
|
12
|
+
import { AcpTransport } from "./transport/acp-transport.ts";
|
|
13
|
+
import {
|
|
14
|
+
parseCapabilities,
|
|
15
|
+
CLIENT_CAPABILITIES,
|
|
16
|
+
type Capabilities,
|
|
17
|
+
} from "./capabilities.ts";
|
|
18
|
+
import { parseConfigOptions, type ConfigOptions } from "./config-options.ts";
|
|
19
|
+
import { extractChunkText, toActivityEvent } from "./updates.ts";
|
|
20
|
+
import { NotConnectedError } from "./errors.ts";
|
|
21
|
+
import { noopLogger, type Logger } from "./logger.ts";
|
|
22
|
+
import type { AgentClient, InterruptOptions } from "./agent-client.ts";
|
|
23
|
+
import type {
|
|
24
|
+
PromptResult,
|
|
25
|
+
PromptHandlers,
|
|
26
|
+
PermissionRequest,
|
|
27
|
+
PermissionOutcome,
|
|
28
|
+
Attachment,
|
|
29
|
+
SessionListPage,
|
|
30
|
+
AgentCommand,
|
|
31
|
+
} from "./types.ts";
|
|
32
|
+
|
|
33
|
+
export interface AcpClientConfig {
|
|
34
|
+
/** How to launch the agent binary. */
|
|
35
|
+
adapter: Adapter;
|
|
36
|
+
/** Prefix merged before the adapter command, e.g. ["docker","exec","-i","<ctr>"]. */
|
|
37
|
+
execPrefix?: string[];
|
|
38
|
+
/** Extra env vars injected at spawn time (never sent over the protocol). */
|
|
39
|
+
env?: Record<string, string>;
|
|
40
|
+
/** Agent workspace — passed to session/new. Also the spawn cwd unless using docker exec. */
|
|
41
|
+
cwd?: string;
|
|
42
|
+
/** Resume this session id on connect() (falls back to a new session on failure). */
|
|
43
|
+
sessionId?: string;
|
|
44
|
+
/** Fallback when a prompt has no onPermissionRequest handler. Default "cancel". */
|
|
45
|
+
defaultPermission?: "approve" | "cancel";
|
|
46
|
+
/** Identification sent in initialize. */
|
|
47
|
+
clientInfo?: { name: string; title?: string; version?: string };
|
|
48
|
+
/** Diagnostics sink. Omit for a silent library. */
|
|
49
|
+
logger?: Logger;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface StartSessionOptions {
|
|
53
|
+
/** Resume this session (falls back to a new one on failure). Defaults to config.sessionId. */
|
|
54
|
+
sessionId?: string;
|
|
55
|
+
/** MCP servers bound at session creation. */
|
|
56
|
+
mcpServers?: schema.McpServer[];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface ListSessionsOptions {
|
|
60
|
+
/** Filter by working directory. Defaults to config.cwd. */
|
|
61
|
+
cwd?: string;
|
|
62
|
+
/** Pagination cursor from a previous page's nextCursor. */
|
|
63
|
+
cursor?: string;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface ConnectResult {
|
|
67
|
+
sessionId: string;
|
|
68
|
+
/** true = resumed an existing session; false = started fresh (incl. resume fallback). */
|
|
69
|
+
resumed: boolean;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface SwitchSessionOptions {
|
|
73
|
+
/** MCP servers bound while loading/resuming/forking the target session. */
|
|
74
|
+
mcpServers?: schema.McpServer[];
|
|
75
|
+
/** Additional absolute workspace roots to activate for the target session. */
|
|
76
|
+
additionalDirectories?: string[];
|
|
77
|
+
/** Raw session updates emitted while switching sessions, e.g. session/load replay. */
|
|
78
|
+
onUpdate?: (notification: unknown) => void;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
interface QueueItem {
|
|
82
|
+
text: string;
|
|
83
|
+
handlers?: PromptHandlers;
|
|
84
|
+
attachments?: Attachment[];
|
|
85
|
+
resolve: (r: PromptResult) => void;
|
|
86
|
+
reject: (e: unknown) => void;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export class AcpClient implements AgentClient {
|
|
90
|
+
private transport: AcpTransport | null = null;
|
|
91
|
+
private _capabilities: Capabilities | null = null;
|
|
92
|
+
private _configOptions: ConfigOptions = new Map();
|
|
93
|
+
private _agentCommands: AgentCommand[] = [];
|
|
94
|
+
private _sessionId: string | null = null;
|
|
95
|
+
|
|
96
|
+
// Per-turn streaming state (only the in-flight turn).
|
|
97
|
+
private active: {
|
|
98
|
+
chunks: string[];
|
|
99
|
+
handlers?: PromptHandlers;
|
|
100
|
+
cancelled: boolean;
|
|
101
|
+
} | null = null;
|
|
102
|
+
|
|
103
|
+
// Session switch replay state (session/load may stream previous conversation history).
|
|
104
|
+
private replay: {
|
|
105
|
+
sessionId: string;
|
|
106
|
+
onUpdate?: (notification: unknown) => void;
|
|
107
|
+
} | null = null;
|
|
108
|
+
|
|
109
|
+
// Serialized prompt queue.
|
|
110
|
+
private queue: QueueItem[] = [];
|
|
111
|
+
private pumping = false;
|
|
112
|
+
|
|
113
|
+
// While authenticating, agent stderr (login URL / device code) is teed here so the
|
|
114
|
+
// caller can show it — auth output almost always arrives on stderr, not the protocol.
|
|
115
|
+
private authStderrSink: ((line: string) => void) | null = null;
|
|
116
|
+
|
|
117
|
+
private readonly log: Logger;
|
|
118
|
+
|
|
119
|
+
constructor(private config: AcpClientConfig) {
|
|
120
|
+
this.log = config.logger ?? noopLogger;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// --- introspection (populated by connect) -------------------------------------
|
|
124
|
+
|
|
125
|
+
get capabilities(): Capabilities {
|
|
126
|
+
if (!this._capabilities) throw new NotConnectedError();
|
|
127
|
+
return this._capabilities;
|
|
128
|
+
}
|
|
129
|
+
get configOptions(): ConfigOptions {
|
|
130
|
+
return this._configOptions;
|
|
131
|
+
}
|
|
132
|
+
/** Auth methods the agent advertised. Empty does NOT mean authenticated (state is opaque). */
|
|
133
|
+
get authMethods(): Capabilities["authMethods"] {
|
|
134
|
+
return this._capabilities?.authMethods ?? [];
|
|
135
|
+
}
|
|
136
|
+
/** Slash commands the agent exposes (from available_commands_update). Reach via `//name`. */
|
|
137
|
+
get agentCommands(): AgentCommand[] {
|
|
138
|
+
return this._agentCommands;
|
|
139
|
+
}
|
|
140
|
+
get currentSessionId(): string | null {
|
|
141
|
+
return this._sessionId;
|
|
142
|
+
}
|
|
143
|
+
/** True once connect() has spawned + initialized (a session may not exist yet). */
|
|
144
|
+
get isConnected(): boolean {
|
|
145
|
+
return this.transport !== null;
|
|
146
|
+
}
|
|
147
|
+
/** True once a session has been created or loaded. */
|
|
148
|
+
get hasSession(): boolean {
|
|
149
|
+
return this._sessionId !== null;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// --- lifecycle ----------------------------------------------------------------
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Spawn the agent and initialize the connection. Populates `capabilities`. Does NOT
|
|
156
|
+
* create a session — call startSession() (or just prompt(), which lazily starts one),
|
|
157
|
+
* or listSessions() to pick an existing one first.
|
|
158
|
+
*/
|
|
159
|
+
async connect(): Promise<Capabilities> {
|
|
160
|
+
if (this.transport) return this.capabilities;
|
|
161
|
+
|
|
162
|
+
const command = buildSpawnCommand(this.config.adapter, this.config.execPrefix);
|
|
163
|
+
const isDockerExec = command[0] === "docker";
|
|
164
|
+
|
|
165
|
+
this.log.info("connect", { command, dockerExec: isDockerExec });
|
|
166
|
+
|
|
167
|
+
const transport = new AcpTransport({
|
|
168
|
+
command,
|
|
169
|
+
// docker exec resolves paths inside the container's namespace — don't pass a host cwd.
|
|
170
|
+
cwd: isDockerExec ? undefined : this.config.cwd,
|
|
171
|
+
env: this.config.env,
|
|
172
|
+
onUpdate: (n) => this.handleUpdate(n),
|
|
173
|
+
onPermissionRequest: (p) => this.handlePermission(p),
|
|
174
|
+
onStderr: (line) => {
|
|
175
|
+
this.log.debug("agent_stderr", { line });
|
|
176
|
+
this.authStderrSink?.(line);
|
|
177
|
+
},
|
|
178
|
+
onCrash: (code) => {
|
|
179
|
+
this.transport = null;
|
|
180
|
+
this._sessionId = null;
|
|
181
|
+
this.log.error("process_exit", { code });
|
|
182
|
+
},
|
|
183
|
+
});
|
|
184
|
+
await transport.start();
|
|
185
|
+
this.transport = transport;
|
|
186
|
+
|
|
187
|
+
const init = await transport.raceExit(
|
|
188
|
+
transport.initialize({
|
|
189
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
190
|
+
clientCapabilities: CLIENT_CAPABILITIES as unknown as schema.ClientCapabilities,
|
|
191
|
+
clientInfo: this.config.clientInfo ?? {
|
|
192
|
+
name: "acp-lib",
|
|
193
|
+
title: "ACP Lib",
|
|
194
|
+
version: "0.1.0",
|
|
195
|
+
},
|
|
196
|
+
} as schema.InitializeRequest),
|
|
197
|
+
);
|
|
198
|
+
this._capabilities = parseCapabilities(init);
|
|
199
|
+
this.log.info("initialized", {
|
|
200
|
+
agent: this._capabilities.agentInfo?.name,
|
|
201
|
+
protocolVersion: this._capabilities.protocolVersion,
|
|
202
|
+
loadSession: this._capabilities.agent.loadSession,
|
|
203
|
+
});
|
|
204
|
+
this.log.debug("initialize_response", { response: init });
|
|
205
|
+
return this._capabilities;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Create a new session, or resume one (sessionId from the option or config). On resume
|
|
210
|
+
* failure, falls back to a new session. Populates `configOptions`.
|
|
211
|
+
*/
|
|
212
|
+
async startSession(options: StartSessionOptions = {}): Promise<ConnectResult> {
|
|
213
|
+
const transport = this.requireTransport();
|
|
214
|
+
const mcpServers = options.mcpServers ?? [];
|
|
215
|
+
const cwd = this.config.cwd ?? process.cwd();
|
|
216
|
+
const resumeId = options.sessionId ?? this.config.sessionId;
|
|
217
|
+
|
|
218
|
+
let resumed = false;
|
|
219
|
+
let sessionId: string;
|
|
220
|
+
|
|
221
|
+
if (resumeId && this.capabilities.agent.loadSession) {
|
|
222
|
+
try {
|
|
223
|
+
await transport.loadSession({ sessionId: resumeId, cwd, mcpServers } as schema.LoadSessionRequest);
|
|
224
|
+
sessionId = resumeId;
|
|
225
|
+
resumed = true;
|
|
226
|
+
this.log.info("session_loaded", { sessionId });
|
|
227
|
+
} catch (err) {
|
|
228
|
+
this.log.warn("session_load_failed", { sessionId: resumeId, error: String(err) });
|
|
229
|
+
sessionId = await this.newSessionInternal(transport, cwd, mcpServers);
|
|
230
|
+
}
|
|
231
|
+
} else {
|
|
232
|
+
sessionId = await this.newSessionInternal(transport, cwd, mcpServers);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
this._sessionId = sessionId;
|
|
236
|
+
return { sessionId, resumed };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Load an existing session and replay its history if the agent supports session/load. */
|
|
240
|
+
async loadSession(
|
|
241
|
+
sessionId: string,
|
|
242
|
+
options: SwitchSessionOptions = {},
|
|
243
|
+
): Promise<ConnectResult> {
|
|
244
|
+
const transport = this.requireTransport();
|
|
245
|
+
if (!this.capabilities.agent.loadSession) {
|
|
246
|
+
throw new Error("agent does not advertise session/load (loadSession)");
|
|
247
|
+
}
|
|
248
|
+
this.replay = { sessionId, onUpdate: options.onUpdate };
|
|
249
|
+
let res: schema.LoadSessionResponse;
|
|
250
|
+
try {
|
|
251
|
+
res = await transport.loadSession({
|
|
252
|
+
sessionId,
|
|
253
|
+
cwd: this.config.cwd ?? process.cwd(),
|
|
254
|
+
mcpServers: options.mcpServers ?? [],
|
|
255
|
+
additionalDirectories: options.additionalDirectories,
|
|
256
|
+
} as schema.LoadSessionRequest);
|
|
257
|
+
} finally {
|
|
258
|
+
this.replay = null;
|
|
259
|
+
}
|
|
260
|
+
this._sessionId = sessionId;
|
|
261
|
+
this._configOptions = parseConfigOptions(res.configOptions);
|
|
262
|
+
this.log.info("session_loaded", {
|
|
263
|
+
sessionId,
|
|
264
|
+
configOptions: [...this._configOptions.keys()],
|
|
265
|
+
});
|
|
266
|
+
this.log.debug("session_load_response", { response: res });
|
|
267
|
+
return { sessionId, resumed: true };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Resume an existing session without replaying history, when advertised by the agent. */
|
|
271
|
+
async resumeSession(
|
|
272
|
+
sessionId: string,
|
|
273
|
+
options: SwitchSessionOptions = {},
|
|
274
|
+
): Promise<ConnectResult> {
|
|
275
|
+
const transport = this.requireTransport();
|
|
276
|
+
if (!this.capabilities.agent.sessionCapabilities.resume) {
|
|
277
|
+
throw new Error("agent does not advertise session/resume (sessionCapabilities.resume)");
|
|
278
|
+
}
|
|
279
|
+
this.replay = { sessionId, onUpdate: options.onUpdate };
|
|
280
|
+
let res: schema.ResumeSessionResponse;
|
|
281
|
+
try {
|
|
282
|
+
res = await transport.resumeSession({
|
|
283
|
+
sessionId,
|
|
284
|
+
cwd: this.config.cwd ?? process.cwd(),
|
|
285
|
+
mcpServers: options.mcpServers ?? [],
|
|
286
|
+
additionalDirectories: options.additionalDirectories,
|
|
287
|
+
} as schema.ResumeSessionRequest);
|
|
288
|
+
} finally {
|
|
289
|
+
this.replay = null;
|
|
290
|
+
}
|
|
291
|
+
this._sessionId = sessionId;
|
|
292
|
+
this._configOptions = parseConfigOptions(res.configOptions);
|
|
293
|
+
this.log.info("session_resumed", {
|
|
294
|
+
sessionId,
|
|
295
|
+
configOptions: [...this._configOptions.keys()],
|
|
296
|
+
});
|
|
297
|
+
this.log.debug("session_resume_response", { response: res });
|
|
298
|
+
return { sessionId, resumed: true };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Fork an existing session and switch this client to the newly-created fork. */
|
|
302
|
+
async forkSession(
|
|
303
|
+
sessionId: string,
|
|
304
|
+
options: SwitchSessionOptions = {},
|
|
305
|
+
): Promise<ConnectResult> {
|
|
306
|
+
const transport = this.requireTransport();
|
|
307
|
+
if (!this.capabilities.agent.sessionCapabilities.fork) {
|
|
308
|
+
throw new Error("agent does not advertise session/fork (sessionCapabilities.fork)");
|
|
309
|
+
}
|
|
310
|
+
this.replay = { sessionId, onUpdate: options.onUpdate };
|
|
311
|
+
let res: schema.ForkSessionResponse;
|
|
312
|
+
try {
|
|
313
|
+
res = await transport.forkSession({
|
|
314
|
+
sessionId,
|
|
315
|
+
cwd: this.config.cwd ?? process.cwd(),
|
|
316
|
+
mcpServers: options.mcpServers ?? [],
|
|
317
|
+
additionalDirectories: options.additionalDirectories,
|
|
318
|
+
} as schema.ForkSessionRequest);
|
|
319
|
+
} finally {
|
|
320
|
+
this.replay = null;
|
|
321
|
+
}
|
|
322
|
+
this._sessionId = res.sessionId;
|
|
323
|
+
this._configOptions = parseConfigOptions(res.configOptions);
|
|
324
|
+
this.log.info("session_forked", {
|
|
325
|
+
fromSessionId: sessionId,
|
|
326
|
+
sessionId: res.sessionId,
|
|
327
|
+
configOptions: [...this._configOptions.keys()],
|
|
328
|
+
});
|
|
329
|
+
this.log.debug("session_fork_response", { response: res });
|
|
330
|
+
return { sessionId: res.sessionId, resumed: false };
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* Ask the AGENT for its sessions (authoritative). Gated by sessionCapabilities.list.
|
|
335
|
+
* Requires connect() but NOT a created session — use it to pick one before starting.
|
|
336
|
+
*/
|
|
337
|
+
async listSessions(options: ListSessionsOptions = {}): Promise<SessionListPage> {
|
|
338
|
+
const transport = this.requireTransport();
|
|
339
|
+
if (!this.capabilities.agent.sessionCapabilities.list) {
|
|
340
|
+
throw new Error("agent does not advertise session/list (sessionCapabilities.list)");
|
|
341
|
+
}
|
|
342
|
+
// Send cwd/cursor ONLY when set. An explicit `cwd: null` is a filter some agents read
|
|
343
|
+
// as "sessions with no cwd" → empty; omitting it means "no filter" (all sessions).
|
|
344
|
+
const params: Record<string, unknown> = {};
|
|
345
|
+
const cwd = options.cwd ?? this.config.cwd;
|
|
346
|
+
if (cwd) params.cwd = cwd;
|
|
347
|
+
if (options.cursor) params.cursor = options.cursor;
|
|
348
|
+
const res = await transport.listSessions(params as schema.ListSessionsRequest);
|
|
349
|
+
this.log.debug("list_sessions_response", { response: res });
|
|
350
|
+
return {
|
|
351
|
+
sessions: (res.sessions ?? []).map((s) => {
|
|
352
|
+
const e = s as Record<string, any>;
|
|
353
|
+
return {
|
|
354
|
+
sessionId: e.sessionId,
|
|
355
|
+
cwd: e.cwd,
|
|
356
|
+
title: e.title ?? undefined,
|
|
357
|
+
updatedAt: e.updatedAt ?? undefined,
|
|
358
|
+
};
|
|
359
|
+
}),
|
|
360
|
+
nextCursor: (res as Record<string, any>).nextCursor ?? undefined,
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* Authenticate the CONNECTION with one of the advertised methods. Connection-level, so
|
|
366
|
+
* it works with or without a session. Auth state is opaque (an agent may answer ok and
|
|
367
|
+
* still be unauthenticated), so this never throws on "wrong" — only on transport errors.
|
|
368
|
+
* `onOutput` receives the agent's stderr during the call (login URL / device code).
|
|
369
|
+
*/
|
|
370
|
+
async authenticate(
|
|
371
|
+
methodId: string,
|
|
372
|
+
handlers: { onOutput?: (line: string) => void } = {},
|
|
373
|
+
): Promise<schema.AuthenticateResponse> {
|
|
374
|
+
const transport = this.requireTransport();
|
|
375
|
+
this.log.info("authenticate", { methodId });
|
|
376
|
+
this.authStderrSink = handlers.onOutput ?? null;
|
|
377
|
+
try {
|
|
378
|
+
const res = await transport.authenticate({ methodId } as schema.AuthenticateRequest);
|
|
379
|
+
this.log.debug("authenticate_response", { response: res });
|
|
380
|
+
return res;
|
|
381
|
+
} finally {
|
|
382
|
+
this.authStderrSink = null;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** Force a brand-new session, ignoring config.sessionId. Useful after authenticating. */
|
|
387
|
+
async newSession(options: { mcpServers?: schema.McpServer[] } = {}): Promise<ConnectResult> {
|
|
388
|
+
const transport = this.requireTransport();
|
|
389
|
+
const cwd = this.config.cwd ?? process.cwd();
|
|
390
|
+
const sessionId = await this.newSessionInternal(transport, cwd, options.mcpServers ?? []);
|
|
391
|
+
this._sessionId = sessionId;
|
|
392
|
+
return { sessionId, resumed: false };
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
private async newSessionInternal(
|
|
396
|
+
transport: AcpTransport,
|
|
397
|
+
cwd: string,
|
|
398
|
+
mcpServers: schema.McpServer[],
|
|
399
|
+
): Promise<string> {
|
|
400
|
+
this._agentCommands = []; // re-populated by the agent's available_commands_update
|
|
401
|
+
const res = await transport.newSession({ cwd, mcpServers } as schema.NewSessionRequest);
|
|
402
|
+
this._configOptions = parseConfigOptions(res.configOptions);
|
|
403
|
+
this.log.info("session_new", {
|
|
404
|
+
sessionId: res.sessionId,
|
|
405
|
+
configOptions: [...this._configOptions.keys()],
|
|
406
|
+
});
|
|
407
|
+
this.log.debug("session_new_response", { response: res });
|
|
408
|
+
return res.sessionId;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
private requireTransport(): AcpTransport {
|
|
412
|
+
if (!this.transport) throw new NotConnectedError();
|
|
413
|
+
return this.transport;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/** Lazily ensure a session exists (used by prompt()). */
|
|
417
|
+
private async ensureSession(): Promise<void> {
|
|
418
|
+
if (!this._sessionId) await this.startSession();
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
async stop(): Promise<void> {
|
|
422
|
+
const t = this.transport;
|
|
423
|
+
this.transport = null;
|
|
424
|
+
this._sessionId = null;
|
|
425
|
+
if (t) await t.stop();
|
|
426
|
+
this.log.info("stopped", {});
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// --- prompting ----------------------------------------------------------------
|
|
430
|
+
|
|
431
|
+
prompt(
|
|
432
|
+
text: string,
|
|
433
|
+
handlers?: PromptHandlers,
|
|
434
|
+
attachments?: Attachment[],
|
|
435
|
+
): Promise<PromptResult> {
|
|
436
|
+
return new Promise<PromptResult>((resolve, reject) => {
|
|
437
|
+
this.queue.push({ text, handlers, attachments, resolve, reject });
|
|
438
|
+
void this.pump();
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
private async pump(): Promise<void> {
|
|
443
|
+
if (this.pumping) return;
|
|
444
|
+
this.pumping = true;
|
|
445
|
+
try {
|
|
446
|
+
while (this.queue.length > 0) {
|
|
447
|
+
const item = this.queue.shift()!;
|
|
448
|
+
try {
|
|
449
|
+
item.resolve(await this.runPrompt(item));
|
|
450
|
+
} catch (err) {
|
|
451
|
+
item.reject(err);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
} finally {
|
|
455
|
+
this.pumping = false;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
private async runPrompt(item: QueueItem): Promise<PromptResult> {
|
|
460
|
+
if (!this.transport) throw new NotConnectedError();
|
|
461
|
+
await this.ensureSession(); // lazily create a session on first prompt
|
|
462
|
+
|
|
463
|
+
const contentBlocks: schema.ContentBlock[] = [];
|
|
464
|
+
if (item.text) contentBlocks.push({ type: "text", text: item.text });
|
|
465
|
+
for (const att of item.attachments ?? []) {
|
|
466
|
+
contentBlocks.push({
|
|
467
|
+
type: "image",
|
|
468
|
+
data: Buffer.from(att.data).toString("base64"),
|
|
469
|
+
mimeType: att.mimeType,
|
|
470
|
+
} as schema.ContentBlock);
|
|
471
|
+
}
|
|
472
|
+
if (contentBlocks.length === 0) contentBlocks.push({ type: "text", text: "" });
|
|
473
|
+
|
|
474
|
+
this.active = { chunks: [], handlers: item.handlers, cancelled: false };
|
|
475
|
+
const t0 = Date.now();
|
|
476
|
+
this.log.debug("prompt_start", { chars: item.text.length });
|
|
477
|
+
this.log.debug("prompt_request", { sessionId: this._sessionId, prompt: contentBlocks });
|
|
478
|
+
try {
|
|
479
|
+
const res = await this.transport.prompt({
|
|
480
|
+
sessionId: this._sessionId,
|
|
481
|
+
prompt: contentBlocks,
|
|
482
|
+
} as schema.PromptRequest);
|
|
483
|
+
this.log.debug("prompt_response", { response: res });
|
|
484
|
+
|
|
485
|
+
const cancelled = this.active.cancelled;
|
|
486
|
+
const text = this.active.chunks.join("");
|
|
487
|
+
this.log[text.length === 0 && !cancelled ? "warn" : "info"]("prompt_end", {
|
|
488
|
+
stopReason: res.stopReason,
|
|
489
|
+
status: cancelled ? "cancelled" : "completed",
|
|
490
|
+
chars: text.length,
|
|
491
|
+
elapsedMs: Date.now() - t0,
|
|
492
|
+
});
|
|
493
|
+
return {
|
|
494
|
+
text,
|
|
495
|
+
stopReason: res.stopReason,
|
|
496
|
+
status: cancelled ? "cancelled" : "completed",
|
|
497
|
+
usage: (res.usage ?? null) as PromptResult["usage"],
|
|
498
|
+
};
|
|
499
|
+
} finally {
|
|
500
|
+
this.active = null;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
interrupt(options: InterruptOptions = {}): void {
|
|
505
|
+
if (options.clearQueue) {
|
|
506
|
+
const dropped = this.queue.splice(0);
|
|
507
|
+
for (const item of dropped) {
|
|
508
|
+
item.resolve({ text: "", stopReason: "cancelled", status: "cancelled", usage: null });
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
if (this.active && this.transport && this._sessionId) {
|
|
512
|
+
this.active.cancelled = true;
|
|
513
|
+
// ACP baseline: session/cancel. The in-flight prompt() then resolves naturally.
|
|
514
|
+
void this.transport.cancel({ sessionId: this._sessionId } as schema.CancelNotification);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
// --- config -------------------------------------------------------------------
|
|
519
|
+
|
|
520
|
+
async setConfig(configId: string, value: unknown): Promise<void> {
|
|
521
|
+
if (!this.transport || !this._sessionId) throw new NotConnectedError();
|
|
522
|
+
const existing = this._configOptions.get(configId);
|
|
523
|
+
const res = await this.transport.setSessionConfigOption({
|
|
524
|
+
sessionId: this._sessionId,
|
|
525
|
+
configId,
|
|
526
|
+
...(existing?.type === "boolean" ? { type: "boolean" } : {}),
|
|
527
|
+
value,
|
|
528
|
+
} as unknown as schema.SetSessionConfigOptionRequest);
|
|
529
|
+
this._configOptions = parseConfigOptions(res.configOptions);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// --- internal handlers --------------------------------------------------------
|
|
533
|
+
|
|
534
|
+
private handleUpdate(notification: schema.SessionNotification): void {
|
|
535
|
+
// Raw protocol trace (logged even outside an active turn, e.g. session/load replay).
|
|
536
|
+
this.log.debug("session_update", { notification });
|
|
537
|
+
|
|
538
|
+
const update = notification.update;
|
|
539
|
+
const kind = (update as Record<string, any>).sessionUpdate;
|
|
540
|
+
if (
|
|
541
|
+
kind === "config_option_update" &&
|
|
542
|
+
(!notification.sessionId || notification.sessionId === this._sessionId)
|
|
543
|
+
) {
|
|
544
|
+
this._configOptions = parseConfigOptions((update as Record<string, any>).configOptions);
|
|
545
|
+
}
|
|
546
|
+
if (kind === "available_commands_update") {
|
|
547
|
+
this._agentCommands = ((update as Record<string, any>).availableCommands ?? []).map(
|
|
548
|
+
(c: Record<string, any>) => ({ name: c.name, description: c.description ?? "" }),
|
|
549
|
+
);
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
if (!this.active) {
|
|
553
|
+
if (this.replay && (!notification.sessionId || notification.sessionId === this.replay.sessionId)) {
|
|
554
|
+
this.replay.onUpdate?.(notification);
|
|
555
|
+
}
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
if (notification.sessionId && notification.sessionId !== this._sessionId) return;
|
|
559
|
+
|
|
560
|
+
const text = extractChunkText(update);
|
|
561
|
+
if (text) {
|
|
562
|
+
this.active.chunks.push(text);
|
|
563
|
+
this.active.handlers?.onChunk?.(text);
|
|
564
|
+
}
|
|
565
|
+
const activity = toActivityEvent(update);
|
|
566
|
+
if (activity) this.active.handlers?.onActivity?.(activity);
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
private async handlePermission(
|
|
570
|
+
params: schema.RequestPermissionRequest,
|
|
571
|
+
): Promise<schema.RequestPermissionResponse> {
|
|
572
|
+
this.log.debug("permission_request", { request: params });
|
|
573
|
+
const handler = this.active?.handlers?.onPermissionRequest;
|
|
574
|
+
const request = toPermissionRequest(params);
|
|
575
|
+
|
|
576
|
+
let outcome: PermissionOutcome;
|
|
577
|
+
if (handler) {
|
|
578
|
+
outcome = await handler(request);
|
|
579
|
+
} else {
|
|
580
|
+
outcome = this.defaultOutcome(request);
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
this.log.debug("permission_response", { outcome });
|
|
584
|
+
if (outcome.outcome === "selected") {
|
|
585
|
+
return { outcome: { outcome: "selected", optionId: outcome.optionId } };
|
|
586
|
+
}
|
|
587
|
+
return { outcome: { outcome: "cancelled" } };
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
private defaultOutcome(request: PermissionRequest): PermissionOutcome {
|
|
591
|
+
if ((this.config.defaultPermission ?? "cancel") === "approve") {
|
|
592
|
+
const first = request.options[0];
|
|
593
|
+
if (first) return { outcome: "selected", optionId: first.optionId };
|
|
594
|
+
}
|
|
595
|
+
return { outcome: "cancelled" };
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
function toPermissionRequest(
|
|
600
|
+
params: schema.RequestPermissionRequest,
|
|
601
|
+
): PermissionRequest {
|
|
602
|
+
const p = params as Record<string, any>;
|
|
603
|
+
return {
|
|
604
|
+
toolCallId: p.toolCall?.toolCallId ?? "",
|
|
605
|
+
title: p.toolCall?.title,
|
|
606
|
+
options: (p.options ?? []).map((o: Record<string, any>) => ({
|
|
607
|
+
optionId: o.optionId,
|
|
608
|
+
name: o.name,
|
|
609
|
+
kind: o.kind,
|
|
610
|
+
})),
|
|
611
|
+
raw: params,
|
|
612
|
+
};
|
|
613
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// Config options (models, reasoning_effort, etc.) — NEVER hardcoded. Discovered from
|
|
2
|
+
// session/new and stored as a Map keyed by configId. See SPEC.md "Config options".
|
|
3
|
+
|
|
4
|
+
import type * as schema from "@agentclientprotocol/sdk";
|
|
5
|
+
|
|
6
|
+
export interface ConfigOptionChoice {
|
|
7
|
+
value: unknown;
|
|
8
|
+
label?: string;
|
|
9
|
+
description?: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface ConfigOption {
|
|
13
|
+
configId: string;
|
|
14
|
+
label?: string;
|
|
15
|
+
description?: string;
|
|
16
|
+
type: "select" | "boolean" | "unknown";
|
|
17
|
+
currentValue: unknown;
|
|
18
|
+
/** For select types: the allowed values. */
|
|
19
|
+
allowedValues?: ConfigOptionChoice[];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type ConfigOptions = Map<string, ConfigOption>;
|
|
23
|
+
|
|
24
|
+
/** Parse the configOptions array returned by session/new into our Map model. */
|
|
25
|
+
export function parseConfigOptions(
|
|
26
|
+
raw: schema.SessionConfigOption[] | null | undefined,
|
|
27
|
+
): ConfigOptions {
|
|
28
|
+
const map: ConfigOptions = new Map();
|
|
29
|
+
for (const o of raw ?? []) {
|
|
30
|
+
const opt = o as Record<string, any>;
|
|
31
|
+
const type: ConfigOption["type"] =
|
|
32
|
+
opt.type === "select" || opt.type === "boolean" ? opt.type : "unknown";
|
|
33
|
+
|
|
34
|
+
const allowedValues: ConfigOptionChoice[] | undefined =
|
|
35
|
+
type === "select" && Array.isArray(opt.options)
|
|
36
|
+
? flattenSelectOptions(opt.options)
|
|
37
|
+
: undefined;
|
|
38
|
+
|
|
39
|
+
map.set(opt.id, {
|
|
40
|
+
configId: opt.id,
|
|
41
|
+
label: opt.name ?? undefined,
|
|
42
|
+
description: opt.description ?? undefined,
|
|
43
|
+
type,
|
|
44
|
+
currentValue: opt.currentValue ?? opt.value,
|
|
45
|
+
allowedValues,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
return map;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function flattenSelectOptions(options: Record<string, any>[]): ConfigOptionChoice[] {
|
|
52
|
+
const choices: ConfigOptionChoice[] = [];
|
|
53
|
+
for (const option of options) {
|
|
54
|
+
if (Array.isArray(option.options)) {
|
|
55
|
+
choices.push(...flattenSelectOptions(option.options));
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
choices.push({
|
|
59
|
+
value: option.value ?? option.id,
|
|
60
|
+
label: option.name ?? option.label,
|
|
61
|
+
description: option.description ?? undefined,
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
return choices;
|
|
65
|
+
}
|