@qlairoslabs/acp-client 0.3.4 → 0.4.1
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/CONSUMER_GUIDE.md +500 -0
- package/README.md +58 -20
- package/package.json +3 -2
- package/src/agent-session.ts +447 -29
- package/src/cli/index.ts +2 -2
- package/src/client.ts +138 -21
- package/src/controller.ts +60 -6
- package/src/index.ts +16 -2
- package/src/repl/agent-session-commands.ts +153 -0
- package/src/repl/commands.ts +18 -16
- package/src/repl/index.ts +14 -6
- package/src/repl/repl.ts +115 -27
- package/src/session-manager.ts +3 -0
- package/src/session-store.ts +2 -1
- package/src/transcript.ts +32 -1
- package/src/types.ts +15 -7
- package/src/updates.ts +23 -8
package/src/client.ts
CHANGED
|
@@ -18,7 +18,7 @@ import {
|
|
|
18
18
|
type ClientCapabilityConfig,
|
|
19
19
|
} from "./capabilities.ts";
|
|
20
20
|
import { parseConfigOptions, type ConfigOptions } from "./config-options.ts";
|
|
21
|
-
import { extractChunkText, toActivityEvent,
|
|
21
|
+
import { extractChunkText, toActivityEvent, toAvailableCommands } from "./updates.ts";
|
|
22
22
|
import { TerminalRegistry } from "./terminals.ts";
|
|
23
23
|
import { readTextFile, writeTextFile } from "./fs-access.ts";
|
|
24
24
|
import { NotConnectedError } from "./errors.ts";
|
|
@@ -32,7 +32,7 @@ import type {
|
|
|
32
32
|
PermissionOutcome,
|
|
33
33
|
Attachment,
|
|
34
34
|
SessionListPage,
|
|
35
|
-
|
|
35
|
+
InternalSessionCommand,
|
|
36
36
|
ToolContent,
|
|
37
37
|
WireEntry,
|
|
38
38
|
} from "./types.ts";
|
|
@@ -46,8 +46,10 @@ export interface AcpClientConfig {
|
|
|
46
46
|
env?: Record<string, string>;
|
|
47
47
|
/** Agent workspace — passed to session/new. Also the spawn cwd unless using docker exec. */
|
|
48
48
|
cwd?: string;
|
|
49
|
-
/** Resume this session id
|
|
49
|
+
/** Resume this session id when startSession() is called. */
|
|
50
50
|
sessionId?: string;
|
|
51
|
+
/** Policy when config.sessionId cannot be loaded. Default "new" for compatibility. */
|
|
52
|
+
sessionLoadFailure?: SessionLoadFailure;
|
|
51
53
|
/** Fallback when a prompt has no onPermissionRequest handler. Default "cancel". */
|
|
52
54
|
defaultPermission?: "approve" | "cancel";
|
|
53
55
|
/** Identification sent in initialize. */
|
|
@@ -69,12 +71,16 @@ export interface AcpClientConfig {
|
|
|
69
71
|
}
|
|
70
72
|
|
|
71
73
|
export interface StartSessionOptions {
|
|
72
|
-
/** Resume this session
|
|
74
|
+
/** Resume this session. Defaults to config.sessionId. */
|
|
73
75
|
sessionId?: string;
|
|
76
|
+
/** What to do when the requested session cannot be loaded. Default config policy, then "new". */
|
|
77
|
+
loadFailure?: SessionLoadFailure;
|
|
74
78
|
/** MCP servers bound at session creation. */
|
|
75
79
|
mcpServers?: schema.McpServer[];
|
|
76
80
|
}
|
|
77
81
|
|
|
82
|
+
export type SessionLoadFailure = "error" | "new";
|
|
83
|
+
|
|
78
84
|
export interface ListSessionsOptions {
|
|
79
85
|
/** Filter by working directory. Defaults to config.cwd. */
|
|
80
86
|
cwd?: string;
|
|
@@ -105,11 +111,20 @@ interface QueueItem {
|
|
|
105
111
|
reject: (e: unknown) => void;
|
|
106
112
|
}
|
|
107
113
|
|
|
114
|
+
export type AvailableCommandsListener = (commands: readonly InternalSessionCommand[]) => void;
|
|
115
|
+
|
|
116
|
+
interface CommandTransition {
|
|
117
|
+
previous: readonly InternalSessionCommand[];
|
|
118
|
+
bySession: Map<string, readonly InternalSessionCommand[]>;
|
|
119
|
+
}
|
|
120
|
+
|
|
108
121
|
export class AcpClient implements AgentClient {
|
|
109
122
|
private transport: AcpTransport | null = null;
|
|
110
123
|
private _capabilities: Capabilities | null = null;
|
|
111
124
|
private _configOptions: ConfigOptions = new Map();
|
|
112
|
-
private
|
|
125
|
+
private _availableCommands: readonly InternalSessionCommand[] = Object.freeze([]);
|
|
126
|
+
private readonly availableCommandListeners = new Set<AvailableCommandsListener>();
|
|
127
|
+
private commandTransition: CommandTransition | null = null;
|
|
113
128
|
private _sessionId: string | null = null;
|
|
114
129
|
|
|
115
130
|
// Per-turn streaming state (only the in-flight turn).
|
|
@@ -157,9 +172,14 @@ export class AcpClient implements AgentClient {
|
|
|
157
172
|
get authMethods(): Capabilities["authMethods"] {
|
|
158
173
|
return this._capabilities?.authMethods ?? [];
|
|
159
174
|
}
|
|
160
|
-
/** Slash commands the
|
|
161
|
-
get
|
|
162
|
-
return this.
|
|
175
|
+
/** Slash commands the active harness exposes (from available_commands_update). */
|
|
176
|
+
get availableCommands(): readonly InternalSessionCommand[] {
|
|
177
|
+
return this._availableCommands;
|
|
178
|
+
}
|
|
179
|
+
/** Observe future command-set changes. Read availableCommands first for the current snapshot. */
|
|
180
|
+
subscribeAvailableCommands(listener: AvailableCommandsListener): () => void {
|
|
181
|
+
this.availableCommandListeners.add(listener);
|
|
182
|
+
return () => this.availableCommandListeners.delete(listener);
|
|
163
183
|
}
|
|
164
184
|
get currentSessionId(): string | null {
|
|
165
185
|
return this._sessionId;
|
|
@@ -222,6 +242,8 @@ export class AcpClient implements AgentClient {
|
|
|
222
242
|
onCrash: (code) => {
|
|
223
243
|
this.transport = null;
|
|
224
244
|
this._sessionId = null;
|
|
245
|
+
this.commandTransition = null;
|
|
246
|
+
this.setAvailableCommands([]);
|
|
225
247
|
this.log.error("process_exit", { code });
|
|
226
248
|
},
|
|
227
249
|
});
|
|
@@ -250,33 +272,36 @@ export class AcpClient implements AgentClient {
|
|
|
250
272
|
}
|
|
251
273
|
|
|
252
274
|
/**
|
|
253
|
-
* Create a new session, or
|
|
254
|
-
*
|
|
275
|
+
* Create a new session, or load one selected by sessionId. `loadFailure` controls
|
|
276
|
+
* whether a failed/unsupported load rejects or explicitly falls back to session/new.
|
|
277
|
+
* Populates `configOptions`.
|
|
255
278
|
*/
|
|
256
279
|
async startSession(options: StartSessionOptions = {}): Promise<ConnectResult> {
|
|
257
280
|
const transport = this.requireTransport();
|
|
258
281
|
const mcpServers = options.mcpServers ?? [];
|
|
259
282
|
const cwd = this.config.cwd ?? process.cwd();
|
|
260
283
|
const resumeId = options.sessionId ?? this.config.sessionId;
|
|
284
|
+
const loadFailure = options.loadFailure ?? this.config.sessionLoadFailure ?? "new";
|
|
261
285
|
|
|
262
286
|
let resumed = false;
|
|
263
287
|
let sessionId: string;
|
|
264
288
|
|
|
265
289
|
if (resumeId && this.capabilities.agent.loadSession) {
|
|
266
290
|
try {
|
|
267
|
-
await
|
|
268
|
-
sessionId =
|
|
269
|
-
resumed =
|
|
270
|
-
this.log.info("session_loaded", { sessionId });
|
|
291
|
+
const result = await this.loadSessionInternal(transport, resumeId, { mcpServers });
|
|
292
|
+
sessionId = result.sessionId;
|
|
293
|
+
resumed = result.resumed;
|
|
271
294
|
} catch (err) {
|
|
272
295
|
this.log.warn("session_load_failed", { sessionId: resumeId, error: String(err) });
|
|
296
|
+
if (loadFailure === "error") throw err;
|
|
273
297
|
sessionId = await this.newSessionInternal(transport, cwd, mcpServers);
|
|
274
298
|
}
|
|
299
|
+
} else if (resumeId && loadFailure === "error") {
|
|
300
|
+
throw new Error("agent does not advertise session/load for the requested internal session");
|
|
275
301
|
} else {
|
|
276
302
|
sessionId = await this.newSessionInternal(transport, cwd, mcpServers);
|
|
277
303
|
}
|
|
278
304
|
|
|
279
|
-
this._sessionId = sessionId;
|
|
280
305
|
return { sessionId, resumed };
|
|
281
306
|
}
|
|
282
307
|
|
|
@@ -289,6 +314,15 @@ export class AcpClient implements AgentClient {
|
|
|
289
314
|
if (!this.capabilities.agent.loadSession) {
|
|
290
315
|
throw new Error("agent does not advertise session/load (loadSession)");
|
|
291
316
|
}
|
|
317
|
+
return this.loadSessionInternal(transport, sessionId, options);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
private async loadSessionInternal(
|
|
321
|
+
transport: AcpTransport,
|
|
322
|
+
sessionId: string,
|
|
323
|
+
options: SwitchSessionOptions = {},
|
|
324
|
+
): Promise<ConnectResult> {
|
|
325
|
+
this.beginCommandTransition();
|
|
292
326
|
this.replay = { sessionId, onUpdate: options.onUpdate };
|
|
293
327
|
let res: schema.LoadSessionResponse;
|
|
294
328
|
try {
|
|
@@ -298,14 +332,19 @@ export class AcpClient implements AgentClient {
|
|
|
298
332
|
mcpServers: options.mcpServers ?? [],
|
|
299
333
|
additionalDirectories: options.additionalDirectories,
|
|
300
334
|
} as schema.LoadSessionRequest);
|
|
335
|
+
} catch (err) {
|
|
336
|
+
this.abortCommandTransition();
|
|
337
|
+
throw err;
|
|
301
338
|
} finally {
|
|
302
339
|
this.replay = null;
|
|
303
340
|
}
|
|
341
|
+
const configOptions = parseConfigOptions(res.configOptions);
|
|
304
342
|
this._sessionId = sessionId;
|
|
305
|
-
this._configOptions =
|
|
343
|
+
this._configOptions = configOptions;
|
|
344
|
+
this.finishCommandTransition(sessionId);
|
|
306
345
|
this.log.info("session_loaded", {
|
|
307
346
|
sessionId,
|
|
308
|
-
configOptions: [...
|
|
347
|
+
configOptions: [...configOptions.keys()],
|
|
309
348
|
});
|
|
310
349
|
this.log.debug("session_load_response", { response: res });
|
|
311
350
|
return { sessionId, resumed: true };
|
|
@@ -320,6 +359,7 @@ export class AcpClient implements AgentClient {
|
|
|
320
359
|
if (!this.capabilities.agent.sessionCapabilities.resume) {
|
|
321
360
|
throw new Error("agent does not advertise session/resume (sessionCapabilities.resume)");
|
|
322
361
|
}
|
|
362
|
+
this.beginCommandTransition();
|
|
323
363
|
this.replay = { sessionId, onUpdate: options.onUpdate };
|
|
324
364
|
let res: schema.ResumeSessionResponse;
|
|
325
365
|
try {
|
|
@@ -329,10 +369,14 @@ export class AcpClient implements AgentClient {
|
|
|
329
369
|
mcpServers: options.mcpServers ?? [],
|
|
330
370
|
additionalDirectories: options.additionalDirectories,
|
|
331
371
|
} as schema.ResumeSessionRequest);
|
|
372
|
+
} catch (err) {
|
|
373
|
+
this.abortCommandTransition();
|
|
374
|
+
throw err;
|
|
332
375
|
} finally {
|
|
333
376
|
this.replay = null;
|
|
334
377
|
}
|
|
335
378
|
this._sessionId = sessionId;
|
|
379
|
+
this.finishCommandTransition(sessionId);
|
|
336
380
|
this._configOptions = parseConfigOptions(res.configOptions);
|
|
337
381
|
this.log.info("session_resumed", {
|
|
338
382
|
sessionId,
|
|
@@ -351,6 +395,7 @@ export class AcpClient implements AgentClient {
|
|
|
351
395
|
if (!this.capabilities.agent.sessionCapabilities.fork) {
|
|
352
396
|
throw new Error("agent does not advertise session/fork (sessionCapabilities.fork)");
|
|
353
397
|
}
|
|
398
|
+
this.beginCommandTransition();
|
|
354
399
|
this.replay = { sessionId, onUpdate: options.onUpdate };
|
|
355
400
|
let res: schema.ForkSessionResponse;
|
|
356
401
|
try {
|
|
@@ -360,10 +405,14 @@ export class AcpClient implements AgentClient {
|
|
|
360
405
|
mcpServers: options.mcpServers ?? [],
|
|
361
406
|
additionalDirectories: options.additionalDirectories,
|
|
362
407
|
} as schema.ForkSessionRequest);
|
|
408
|
+
} catch (err) {
|
|
409
|
+
this.abortCommandTransition();
|
|
410
|
+
throw err;
|
|
363
411
|
} finally {
|
|
364
412
|
this.replay = null;
|
|
365
413
|
}
|
|
366
414
|
this._sessionId = res.sessionId;
|
|
415
|
+
this.finishCommandTransition(res.sessionId);
|
|
367
416
|
this._configOptions = parseConfigOptions(res.configOptions);
|
|
368
417
|
this.log.info("session_forked", {
|
|
369
418
|
fromSessionId: sessionId,
|
|
@@ -432,7 +481,6 @@ export class AcpClient implements AgentClient {
|
|
|
432
481
|
const transport = this.requireTransport();
|
|
433
482
|
const cwd = this.config.cwd ?? process.cwd();
|
|
434
483
|
const sessionId = await this.newSessionInternal(transport, cwd, options.mcpServers ?? []);
|
|
435
|
-
this._sessionId = sessionId;
|
|
436
484
|
return { sessionId, resumed: false };
|
|
437
485
|
}
|
|
438
486
|
|
|
@@ -441,8 +489,16 @@ export class AcpClient implements AgentClient {
|
|
|
441
489
|
cwd: string,
|
|
442
490
|
mcpServers: schema.McpServer[],
|
|
443
491
|
): Promise<string> {
|
|
444
|
-
this.
|
|
445
|
-
|
|
492
|
+
this.beginCommandTransition();
|
|
493
|
+
let res: schema.NewSessionResponse;
|
|
494
|
+
try {
|
|
495
|
+
res = await transport.newSession({ cwd, mcpServers } as schema.NewSessionRequest);
|
|
496
|
+
} catch (err) {
|
|
497
|
+
this.abortCommandTransition();
|
|
498
|
+
throw err;
|
|
499
|
+
}
|
|
500
|
+
this._sessionId = res.sessionId;
|
|
501
|
+
this.finishCommandTransition(res.sessionId);
|
|
446
502
|
this._configOptions = parseConfigOptions(res.configOptions);
|
|
447
503
|
this.log.info("session_new", {
|
|
448
504
|
sessionId: res.sessionId,
|
|
@@ -466,6 +522,8 @@ export class AcpClient implements AgentClient {
|
|
|
466
522
|
const t = this.transport;
|
|
467
523
|
this.transport = null;
|
|
468
524
|
this._sessionId = null;
|
|
525
|
+
this.commandTransition = null;
|
|
526
|
+
this.setAvailableCommands([]);
|
|
469
527
|
this.terminals?.releaseAll();
|
|
470
528
|
this.terminals = null;
|
|
471
529
|
if (t) await t.stop();
|
|
@@ -607,7 +665,16 @@ export class AcpClient implements AgentClient {
|
|
|
607
665
|
this._configOptions = parseConfigOptions((update as Record<string, any>).configOptions);
|
|
608
666
|
}
|
|
609
667
|
if (kind === "available_commands_update") {
|
|
610
|
-
|
|
668
|
+
const commands = toAvailableCommands((update as Record<string, any>).availableCommands);
|
|
669
|
+
const sessionId = notification.sessionId || "";
|
|
670
|
+
if (this.commandTransition) {
|
|
671
|
+
// A session/new notification can precede its response, so the target id is not
|
|
672
|
+
// necessarily known yet. Buffer by wire session id and commit only the response's
|
|
673
|
+
// selected id when the transition finishes.
|
|
674
|
+
if (sessionId) this.commandTransition.bySession.set(sessionId, commands);
|
|
675
|
+
} else if (!sessionId || sessionId === this._sessionId) {
|
|
676
|
+
this.setAvailableCommands(commands);
|
|
677
|
+
}
|
|
611
678
|
}
|
|
612
679
|
|
|
613
680
|
if (!this.active) {
|
|
@@ -688,6 +755,56 @@ export class AcpClient implements AgentClient {
|
|
|
688
755
|
// Nothing recognizable to approve: refuse rather than guess. Guessing is the bug above.
|
|
689
756
|
return allow ? { outcome: "selected", optionId: allow.optionId } : { outcome: "cancelled" };
|
|
690
757
|
}
|
|
758
|
+
|
|
759
|
+
private beginCommandTransition(): void {
|
|
760
|
+
// Session operations are serialized by their callers. Preserve the last snapshot so
|
|
761
|
+
// a failed load/new can roll back without leaving an unrelated empty command palette.
|
|
762
|
+
this.commandTransition = { previous: this._availableCommands, bySession: new Map() };
|
|
763
|
+
this.setAvailableCommands([]);
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
private finishCommandTransition(sessionId: string): void {
|
|
767
|
+
const transition = this.commandTransition;
|
|
768
|
+
this.commandTransition = null;
|
|
769
|
+
this.setAvailableCommands(transition?.bySession.get(sessionId) ?? []);
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
private abortCommandTransition(): void {
|
|
773
|
+
const transition = this.commandTransition;
|
|
774
|
+
this.commandTransition = null;
|
|
775
|
+
if (transition) this.setAvailableCommands(transition.previous);
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
private setAvailableCommands(commands: readonly InternalSessionCommand[]): void {
|
|
779
|
+
if (sameAvailableCommands(this._availableCommands, commands)) return;
|
|
780
|
+
// Never expose the mutable transition scratch arrays used internally. Command
|
|
781
|
+
// objects come from toAvailableCommands() frozen; the copy makes the collection itself
|
|
782
|
+
// immutable as well, including the empty snapshots published between sessions.
|
|
783
|
+
const snapshot: readonly InternalSessionCommand[] = Object.freeze([...commands]);
|
|
784
|
+
this._availableCommands = snapshot;
|
|
785
|
+
for (const listener of [...this.availableCommandListeners]) {
|
|
786
|
+
try {
|
|
787
|
+
listener(snapshot);
|
|
788
|
+
} catch (err) {
|
|
789
|
+
this.log.warn("available_commands_listener_failed", { error: String(err) });
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
function sameAvailableCommands(
|
|
796
|
+
a: readonly InternalSessionCommand[],
|
|
797
|
+
b: readonly InternalSessionCommand[],
|
|
798
|
+
): boolean {
|
|
799
|
+
if (a.length !== b.length) return false;
|
|
800
|
+
return a.every((command, index) => {
|
|
801
|
+
const other = b[index];
|
|
802
|
+
return other != null &&
|
|
803
|
+
command.name === other.name &&
|
|
804
|
+
command.description === other.description &&
|
|
805
|
+
command.input?.kind === other.input?.kind &&
|
|
806
|
+
command.input?.hint === other.input?.hint;
|
|
807
|
+
});
|
|
691
808
|
}
|
|
692
809
|
|
|
693
810
|
function toPermissionRequest(
|
package/src/controller.ts
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
AcpClient,
|
|
3
|
+
type AcpClientConfig,
|
|
4
|
+
type ConnectResult,
|
|
5
|
+
type SessionLoadFailure,
|
|
6
|
+
type SwitchSessionOptions,
|
|
7
|
+
} from "./client.ts";
|
|
2
8
|
import type * as schema from "@agentclientprotocol/sdk";
|
|
3
9
|
import type { Adapter } from "./adapters.ts";
|
|
4
10
|
import type { AgentClient, Bridgeable, BridgeOptions, InterruptOptions } from "./agent-client.ts";
|
|
@@ -6,7 +12,7 @@ import type { Capabilities } from "./capabilities.ts";
|
|
|
6
12
|
import type { ConfigOption, ConfigOptions } from "./config-options.ts";
|
|
7
13
|
import type { Logger } from "./logger.ts";
|
|
8
14
|
import type {
|
|
9
|
-
|
|
15
|
+
InternalSessionCommand,
|
|
10
16
|
Attachment,
|
|
11
17
|
PromptHandlers,
|
|
12
18
|
PromptResult,
|
|
@@ -15,6 +21,8 @@ import type {
|
|
|
15
21
|
} from "./types.ts";
|
|
16
22
|
import { NotConnectedError } from "./errors.ts";
|
|
17
23
|
|
|
24
|
+
const NO_AVAILABLE_COMMANDS: readonly InternalSessionCommand[] = Object.freeze([]);
|
|
25
|
+
|
|
18
26
|
/**
|
|
19
27
|
* How the controller talks to the agent. Orthogonal to `adapter` (which agent):
|
|
20
28
|
* - "normal" → AcpClient: full ACP JSON-RPC (capabilities, config, sessions).
|
|
@@ -35,6 +43,8 @@ export interface AgentControllerConfig {
|
|
|
35
43
|
cwd?: string;
|
|
36
44
|
/** Session id to load on start(). */
|
|
37
45
|
sessionId?: string;
|
|
46
|
+
/** Policy when sessionId cannot be loaded. Default "new" for compatibility. */
|
|
47
|
+
sessionLoadFailure?: SessionLoadFailure;
|
|
38
48
|
/** Default MCP servers bound at session creation/switch, unless a call overrides them. */
|
|
39
49
|
mcpServers?: schema.McpServer[];
|
|
40
50
|
defaultPermission?: "approve" | "cancel";
|
|
@@ -90,6 +100,10 @@ export class AgentController implements AgentClient {
|
|
|
90
100
|
private current: AgentClient | null = null;
|
|
91
101
|
private acp: AcpClient | null = null;
|
|
92
102
|
private mode: AgentMode;
|
|
103
|
+
private readonly availableCommandListeners = new Set<
|
|
104
|
+
(commands: readonly InternalSessionCommand[]) => void
|
|
105
|
+
>();
|
|
106
|
+
private detachAvailableCommands: (() => void) | null = null;
|
|
93
107
|
|
|
94
108
|
constructor(private readonly config: AgentControllerConfig) {
|
|
95
109
|
this.mode = config.mode ?? "normal";
|
|
@@ -131,9 +145,17 @@ export class AgentController implements AgentClient {
|
|
|
131
145
|
return this.acp?.authMethods ?? [];
|
|
132
146
|
}
|
|
133
147
|
|
|
134
|
-
/** Slash commands the
|
|
135
|
-
get
|
|
136
|
-
return this.acp?.
|
|
148
|
+
/** Slash commands the active ACP harness exposes. */
|
|
149
|
+
get availableCommands(): readonly InternalSessionCommand[] {
|
|
150
|
+
return this.acp?.availableCommands ?? NO_AVAILABLE_COMMANDS;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Observe future command-set changes across ACP leaf and mode replacements. */
|
|
154
|
+
subscribeAvailableCommands(
|
|
155
|
+
listener: (commands: readonly InternalSessionCommand[]) => void,
|
|
156
|
+
): () => void {
|
|
157
|
+
this.availableCommandListeners.add(listener);
|
|
158
|
+
return () => this.availableCommandListeners.delete(listener);
|
|
137
159
|
}
|
|
138
160
|
|
|
139
161
|
async start(): Promise<ConnectResult> {
|
|
@@ -143,6 +165,7 @@ export class AgentController implements AgentClient {
|
|
|
143
165
|
const brought = await this.bringUp(this.mode, this.config.sessionId);
|
|
144
166
|
this.current = brought.client;
|
|
145
167
|
this.acp = brought.acp;
|
|
168
|
+
this.attachAvailableCommandSource();
|
|
146
169
|
return brought.result;
|
|
147
170
|
}
|
|
148
171
|
|
|
@@ -190,6 +213,9 @@ export class AgentController implements AgentClient {
|
|
|
190
213
|
const client = this.current;
|
|
191
214
|
this.current = null;
|
|
192
215
|
this.acp = null;
|
|
216
|
+
this.detachAvailableCommands?.();
|
|
217
|
+
this.detachAvailableCommands = null;
|
|
218
|
+
this.emitAvailableCommands(NO_AVAILABLE_COMMANDS);
|
|
193
219
|
if (client) await client.stop();
|
|
194
220
|
}
|
|
195
221
|
|
|
@@ -207,6 +233,7 @@ export class AgentController implements AgentClient {
|
|
|
207
233
|
this.current = brought.client;
|
|
208
234
|
this.acp = brought.acp;
|
|
209
235
|
this.mode = mode;
|
|
236
|
+
this.attachAvailableCommandSource();
|
|
210
237
|
if (previous) await previous.stop();
|
|
211
238
|
return brought.result;
|
|
212
239
|
}
|
|
@@ -372,6 +399,7 @@ export class AgentController implements AgentClient {
|
|
|
372
399
|
env: this.config.env,
|
|
373
400
|
cwd: this.config.cwd,
|
|
374
401
|
sessionId,
|
|
402
|
+
sessionLoadFailure: this.config.sessionLoadFailure,
|
|
375
403
|
defaultPermission: this.config.defaultPermission,
|
|
376
404
|
clientInfo: this.config.clientInfo,
|
|
377
405
|
clientCapabilities: this.config.clientCapabilities,
|
|
@@ -389,8 +417,15 @@ export class AgentController implements AgentClient {
|
|
|
389
417
|
}
|
|
390
418
|
let result: ConnectResult;
|
|
391
419
|
try {
|
|
392
|
-
result = await client.startSession({
|
|
420
|
+
result = await client.startSession({
|
|
421
|
+
mcpServers: this.config.mcpServers,
|
|
422
|
+
loadFailure: this.config.sessionLoadFailure,
|
|
423
|
+
});
|
|
393
424
|
} catch (err) {
|
|
425
|
+
if (sessionId && this.config.sessionLoadFailure === "error") {
|
|
426
|
+
await client.stop();
|
|
427
|
+
throw err;
|
|
428
|
+
}
|
|
394
429
|
this.config.logger?.warn("session_start_failed", { error: String(err) });
|
|
395
430
|
result = { sessionId: "", resumed: false };
|
|
396
431
|
}
|
|
@@ -409,6 +444,25 @@ export class AgentController implements AgentClient {
|
|
|
409
444
|
}
|
|
410
445
|
return this.acp;
|
|
411
446
|
}
|
|
447
|
+
|
|
448
|
+
private attachAvailableCommandSource(): void {
|
|
449
|
+
this.detachAvailableCommands?.();
|
|
450
|
+
this.detachAvailableCommands = this.acp?.subscribeAvailableCommands((commands) =>
|
|
451
|
+
this.emitAvailableCommands(commands)) ?? null;
|
|
452
|
+
this.emitAvailableCommands(this.acp?.availableCommands ?? NO_AVAILABLE_COMMANDS);
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
private emitAvailableCommands(commands: readonly InternalSessionCommand[]): void {
|
|
456
|
+
for (const listener of [...this.availableCommandListeners]) {
|
|
457
|
+
try {
|
|
458
|
+
listener(commands);
|
|
459
|
+
} catch (err) {
|
|
460
|
+
this.config.logger?.warn("controller_available_commands_listener_failed", {
|
|
461
|
+
error: String(err),
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
}
|
|
412
466
|
}
|
|
413
467
|
|
|
414
468
|
export function parseConfigValue(
|
package/src/index.ts
CHANGED
|
@@ -10,6 +10,7 @@ export type {
|
|
|
10
10
|
ListSessionsOptions,
|
|
11
11
|
SwitchSessionOptions,
|
|
12
12
|
ConnectResult,
|
|
13
|
+
SessionLoadFailure,
|
|
13
14
|
} from "./client.ts";
|
|
14
15
|
|
|
15
16
|
export {
|
|
@@ -29,7 +30,18 @@ export type {
|
|
|
29
30
|
} from "./controller.ts";
|
|
30
31
|
|
|
31
32
|
export { AgentSession } from "./agent-session.ts";
|
|
32
|
-
export type {
|
|
33
|
+
export type {
|
|
34
|
+
AgentSessionConfig,
|
|
35
|
+
TranscriptActivityConfig,
|
|
36
|
+
AgentSessionPhase,
|
|
37
|
+
AgentSessionState,
|
|
38
|
+
AgentSessionEvent,
|
|
39
|
+
AgentSessionNotification,
|
|
40
|
+
AgentSessionListener,
|
|
41
|
+
HandoffOptions,
|
|
42
|
+
HandoffResult,
|
|
43
|
+
ProviderSession,
|
|
44
|
+
} from "./agent-session.ts";
|
|
33
45
|
|
|
34
46
|
export type {
|
|
35
47
|
AgentClient,
|
|
@@ -105,6 +117,7 @@ export type {
|
|
|
105
117
|
TranscriptMetaLine,
|
|
106
118
|
TranscriptPermissionLine,
|
|
107
119
|
TranscriptRawLine,
|
|
120
|
+
TranscriptHandoffLine,
|
|
108
121
|
TranscriptRole,
|
|
109
122
|
} from "./transcript.ts";
|
|
110
123
|
|
|
@@ -134,6 +147,7 @@ export type {
|
|
|
134
147
|
Attachment,
|
|
135
148
|
SessionListEntry,
|
|
136
149
|
SessionListPage,
|
|
137
|
-
|
|
150
|
+
InternalSessionCommand,
|
|
151
|
+
InternalSessionCommandInput,
|
|
138
152
|
WireEntry,
|
|
139
153
|
} from "./types.ts";
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// Opinionated local commands for a REPL bound to one stable AgentSession. This layer
|
|
2
|
+
// never selects a different logical AgentSession; a managed consumer/CLI owns that.
|
|
3
|
+
|
|
4
|
+
import type { AgentClient, Bridgeable } from "../agent-client.ts";
|
|
5
|
+
import type {
|
|
6
|
+
AgentSessionPhase,
|
|
7
|
+
AgentSessionState,
|
|
8
|
+
HandoffOptions,
|
|
9
|
+
HandoffResult,
|
|
10
|
+
} from "../agent-session.ts";
|
|
11
|
+
import type { AgentMode } from "../controller.ts";
|
|
12
|
+
import type { InternalSessionCommand, PromptHandlers, PromptResult } from "../types.ts";
|
|
13
|
+
import { runRepl, type ReplOptions } from "./repl.ts";
|
|
14
|
+
|
|
15
|
+
/** Structural surface used by the command set, allowing focused consumer test doubles. */
|
|
16
|
+
export interface InteractiveAgentSession extends AgentClient, Bridgeable {
|
|
17
|
+
readonly agentSessionId: string;
|
|
18
|
+
readonly internalSessionId: string | null;
|
|
19
|
+
readonly adapterId: string;
|
|
20
|
+
readonly mode: AgentMode;
|
|
21
|
+
readonly state: AgentSessionState;
|
|
22
|
+
readonly isBusy: boolean;
|
|
23
|
+
readonly queuedOperationCount: number;
|
|
24
|
+
readonly transcriptPath?: string;
|
|
25
|
+
readonly internalSessionCommands: readonly InternalSessionCommand[];
|
|
26
|
+
handoff(options?: HandoffOptions): Promise<HandoffResult>;
|
|
27
|
+
executeInternalSessionCommand(
|
|
28
|
+
name: string,
|
|
29
|
+
input?: string,
|
|
30
|
+
handlers?: PromptHandlers,
|
|
31
|
+
): Promise<PromptResult>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface AgentSessionCommandHandlerDeps {
|
|
35
|
+
session: InteractiveAgentSession;
|
|
36
|
+
note: (message: string) => void;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface AgentSessionCommandHandlers {
|
|
40
|
+
onSlashCommand(command: string, args: string[]): Promise<boolean>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Commands that control exactly one stable logical AgentSession. */
|
|
44
|
+
export function createAgentSessionCommands(
|
|
45
|
+
deps: AgentSessionCommandHandlerDeps,
|
|
46
|
+
): AgentSessionCommandHandlers {
|
|
47
|
+
const { session, note } = deps;
|
|
48
|
+
|
|
49
|
+
const onSlashCommand = async (command: string, args: string[]): Promise<boolean> => {
|
|
50
|
+
switch (command) {
|
|
51
|
+
case "help":
|
|
52
|
+
note("local commands: /help /session /state /commands /handoff [SUMMARY] /bridge /exit");
|
|
53
|
+
note("internal session commands: //name [input]");
|
|
54
|
+
return true;
|
|
55
|
+
|
|
56
|
+
case "session":
|
|
57
|
+
note(`agentSessionId=${session.agentSessionId}`);
|
|
58
|
+
note(`internalSessionId=${session.internalSessionId ?? "(none)"}`);
|
|
59
|
+
note(`adapter=${session.adapterId} mode=${session.mode}`);
|
|
60
|
+
if (session.transcriptPath) note(`transcript=${session.transcriptPath}`);
|
|
61
|
+
return true;
|
|
62
|
+
|
|
63
|
+
case "state":
|
|
64
|
+
note(formatState(session.state));
|
|
65
|
+
return true;
|
|
66
|
+
|
|
67
|
+
case "commands":
|
|
68
|
+
if (session.internalSessionCommands.length === 0) {
|
|
69
|
+
note("(no internal session commands advertised; //name is still explicit)");
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
note("internal session commands:");
|
|
73
|
+
for (const available of session.internalSessionCommands) {
|
|
74
|
+
const input = available.input?.hint ? ` ${available.input.hint}` : "";
|
|
75
|
+
const description = available.description ? ` — ${available.description}` : "";
|
|
76
|
+
note(` //${available.name}${input}${description}`);
|
|
77
|
+
}
|
|
78
|
+
return true;
|
|
79
|
+
|
|
80
|
+
case "handoff": {
|
|
81
|
+
const summary = args.join(" ").trim();
|
|
82
|
+
try {
|
|
83
|
+
const result = await session.handoff(summary ? { summary } : undefined);
|
|
84
|
+
note(
|
|
85
|
+
`handoff ${result.handoffId}: ${result.fromInternalSessionId ?? "(none)"} -> ` +
|
|
86
|
+
result.toInternalSessionId,
|
|
87
|
+
);
|
|
88
|
+
} catch (error) {
|
|
89
|
+
note(`handoff failed: ${String(error)}`);
|
|
90
|
+
}
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
case "bridge":
|
|
95
|
+
try {
|
|
96
|
+
await session.bridge();
|
|
97
|
+
} catch (error) {
|
|
98
|
+
note(`bridge failed: ${String(error)}`);
|
|
99
|
+
}
|
|
100
|
+
return true;
|
|
101
|
+
|
|
102
|
+
default:
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
return { onSlashCommand };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export interface AgentSessionReplOptions
|
|
111
|
+
extends Omit<ReplOptions, "onSlashCommand" | "onInternalSessionCommand"> {
|
|
112
|
+
/** Output for local command results. Default stderr. */
|
|
113
|
+
note?: (message: string) => void;
|
|
114
|
+
/** Optional consumer-local extension, tried after the built-in single-session set. */
|
|
115
|
+
onSlashCommand?: ReplOptions["onSlashCommand"];
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Run the opinionated REPL for one stable AgentSession. The caller retains lifecycle
|
|
120
|
+
* ownership and must stop the session when appropriate.
|
|
121
|
+
*/
|
|
122
|
+
export function runAgentSessionRepl(
|
|
123
|
+
session: InteractiveAgentSession,
|
|
124
|
+
options: AgentSessionReplOptions = {},
|
|
125
|
+
): Promise<void> {
|
|
126
|
+
const note = options.note ?? ((message: string) => process.stderr.write(`${message}\n`));
|
|
127
|
+
const builtIn = createAgentSessionCommands({ session, note });
|
|
128
|
+
const extension = options.onSlashCommand;
|
|
129
|
+
const { note: _note, onSlashCommand: _extension, ...replOptions } = options;
|
|
130
|
+
|
|
131
|
+
return runRepl(session, {
|
|
132
|
+
...replOptions,
|
|
133
|
+
intro: options.intro ??
|
|
134
|
+
`AgentSession ${session.agentSessionId} (${session.adapterId}) · /help · //name for internal commands`,
|
|
135
|
+
onSlashCommand: async (command, args) => {
|
|
136
|
+
if (await builtIn.onSlashCommand(command, args)) return true;
|
|
137
|
+
return await extension?.(command, args) === true;
|
|
138
|
+
},
|
|
139
|
+
onInternalSessionCommand: (command, input, handlers) =>
|
|
140
|
+
session.executeInternalSessionCommand(command, input, handlers),
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function formatState(state: AgentSessionState): string {
|
|
145
|
+
const phase: AgentSessionPhase = state.phase;
|
|
146
|
+
return [
|
|
147
|
+
`phase=${phase}`,
|
|
148
|
+
`busy=${state.isBusy}`,
|
|
149
|
+
`queued=${state.queuedOperationCount}`,
|
|
150
|
+
`internalSessionId=${state.internalSessionId ?? "(none)"}`,
|
|
151
|
+
`mode=${state.mode}`,
|
|
152
|
+
].join(" ");
|
|
153
|
+
}
|