@qlairoslabs/acp-client 0.3.4 → 0.4.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/README.md +54 -20
- package/package.json +1 -1
- package/src/agent-session.ts +447 -29
- package/src/cli/index.ts +2 -2
- package/src/client.ts +128 -15
- 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,41 @@ 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) {
|
|
290
|
+
this.beginCommandTransition();
|
|
266
291
|
try {
|
|
267
292
|
await transport.loadSession({ sessionId: resumeId, cwd, mcpServers } as schema.LoadSessionRequest);
|
|
268
293
|
sessionId = resumeId;
|
|
294
|
+
this._sessionId = sessionId;
|
|
295
|
+
this.finishCommandTransition(sessionId);
|
|
269
296
|
resumed = true;
|
|
270
297
|
this.log.info("session_loaded", { sessionId });
|
|
271
298
|
} catch (err) {
|
|
299
|
+
this.abortCommandTransition();
|
|
272
300
|
this.log.warn("session_load_failed", { sessionId: resumeId, error: String(err) });
|
|
301
|
+
if (loadFailure === "error") throw err;
|
|
273
302
|
sessionId = await this.newSessionInternal(transport, cwd, mcpServers);
|
|
274
303
|
}
|
|
304
|
+
} else if (resumeId && loadFailure === "error") {
|
|
305
|
+
throw new Error("agent does not advertise session/load for the requested internal session");
|
|
275
306
|
} else {
|
|
276
307
|
sessionId = await this.newSessionInternal(transport, cwd, mcpServers);
|
|
277
308
|
}
|
|
278
309
|
|
|
279
|
-
this._sessionId = sessionId;
|
|
280
310
|
return { sessionId, resumed };
|
|
281
311
|
}
|
|
282
312
|
|
|
@@ -289,6 +319,7 @@ export class AcpClient implements AgentClient {
|
|
|
289
319
|
if (!this.capabilities.agent.loadSession) {
|
|
290
320
|
throw new Error("agent does not advertise session/load (loadSession)");
|
|
291
321
|
}
|
|
322
|
+
this.beginCommandTransition();
|
|
292
323
|
this.replay = { sessionId, onUpdate: options.onUpdate };
|
|
293
324
|
let res: schema.LoadSessionResponse;
|
|
294
325
|
try {
|
|
@@ -298,10 +329,14 @@ export class AcpClient implements AgentClient {
|
|
|
298
329
|
mcpServers: options.mcpServers ?? [],
|
|
299
330
|
additionalDirectories: options.additionalDirectories,
|
|
300
331
|
} as schema.LoadSessionRequest);
|
|
332
|
+
} catch (err) {
|
|
333
|
+
this.abortCommandTransition();
|
|
334
|
+
throw err;
|
|
301
335
|
} finally {
|
|
302
336
|
this.replay = null;
|
|
303
337
|
}
|
|
304
338
|
this._sessionId = sessionId;
|
|
339
|
+
this.finishCommandTransition(sessionId);
|
|
305
340
|
this._configOptions = parseConfigOptions(res.configOptions);
|
|
306
341
|
this.log.info("session_loaded", {
|
|
307
342
|
sessionId,
|
|
@@ -320,6 +355,7 @@ export class AcpClient implements AgentClient {
|
|
|
320
355
|
if (!this.capabilities.agent.sessionCapabilities.resume) {
|
|
321
356
|
throw new Error("agent does not advertise session/resume (sessionCapabilities.resume)");
|
|
322
357
|
}
|
|
358
|
+
this.beginCommandTransition();
|
|
323
359
|
this.replay = { sessionId, onUpdate: options.onUpdate };
|
|
324
360
|
let res: schema.ResumeSessionResponse;
|
|
325
361
|
try {
|
|
@@ -329,10 +365,14 @@ export class AcpClient implements AgentClient {
|
|
|
329
365
|
mcpServers: options.mcpServers ?? [],
|
|
330
366
|
additionalDirectories: options.additionalDirectories,
|
|
331
367
|
} as schema.ResumeSessionRequest);
|
|
368
|
+
} catch (err) {
|
|
369
|
+
this.abortCommandTransition();
|
|
370
|
+
throw err;
|
|
332
371
|
} finally {
|
|
333
372
|
this.replay = null;
|
|
334
373
|
}
|
|
335
374
|
this._sessionId = sessionId;
|
|
375
|
+
this.finishCommandTransition(sessionId);
|
|
336
376
|
this._configOptions = parseConfigOptions(res.configOptions);
|
|
337
377
|
this.log.info("session_resumed", {
|
|
338
378
|
sessionId,
|
|
@@ -351,6 +391,7 @@ export class AcpClient implements AgentClient {
|
|
|
351
391
|
if (!this.capabilities.agent.sessionCapabilities.fork) {
|
|
352
392
|
throw new Error("agent does not advertise session/fork (sessionCapabilities.fork)");
|
|
353
393
|
}
|
|
394
|
+
this.beginCommandTransition();
|
|
354
395
|
this.replay = { sessionId, onUpdate: options.onUpdate };
|
|
355
396
|
let res: schema.ForkSessionResponse;
|
|
356
397
|
try {
|
|
@@ -360,10 +401,14 @@ export class AcpClient implements AgentClient {
|
|
|
360
401
|
mcpServers: options.mcpServers ?? [],
|
|
361
402
|
additionalDirectories: options.additionalDirectories,
|
|
362
403
|
} as schema.ForkSessionRequest);
|
|
404
|
+
} catch (err) {
|
|
405
|
+
this.abortCommandTransition();
|
|
406
|
+
throw err;
|
|
363
407
|
} finally {
|
|
364
408
|
this.replay = null;
|
|
365
409
|
}
|
|
366
410
|
this._sessionId = res.sessionId;
|
|
411
|
+
this.finishCommandTransition(res.sessionId);
|
|
367
412
|
this._configOptions = parseConfigOptions(res.configOptions);
|
|
368
413
|
this.log.info("session_forked", {
|
|
369
414
|
fromSessionId: sessionId,
|
|
@@ -432,7 +477,6 @@ export class AcpClient implements AgentClient {
|
|
|
432
477
|
const transport = this.requireTransport();
|
|
433
478
|
const cwd = this.config.cwd ?? process.cwd();
|
|
434
479
|
const sessionId = await this.newSessionInternal(transport, cwd, options.mcpServers ?? []);
|
|
435
|
-
this._sessionId = sessionId;
|
|
436
480
|
return { sessionId, resumed: false };
|
|
437
481
|
}
|
|
438
482
|
|
|
@@ -441,8 +485,16 @@ export class AcpClient implements AgentClient {
|
|
|
441
485
|
cwd: string,
|
|
442
486
|
mcpServers: schema.McpServer[],
|
|
443
487
|
): Promise<string> {
|
|
444
|
-
this.
|
|
445
|
-
|
|
488
|
+
this.beginCommandTransition();
|
|
489
|
+
let res: schema.NewSessionResponse;
|
|
490
|
+
try {
|
|
491
|
+
res = await transport.newSession({ cwd, mcpServers } as schema.NewSessionRequest);
|
|
492
|
+
} catch (err) {
|
|
493
|
+
this.abortCommandTransition();
|
|
494
|
+
throw err;
|
|
495
|
+
}
|
|
496
|
+
this._sessionId = res.sessionId;
|
|
497
|
+
this.finishCommandTransition(res.sessionId);
|
|
446
498
|
this._configOptions = parseConfigOptions(res.configOptions);
|
|
447
499
|
this.log.info("session_new", {
|
|
448
500
|
sessionId: res.sessionId,
|
|
@@ -466,6 +518,8 @@ export class AcpClient implements AgentClient {
|
|
|
466
518
|
const t = this.transport;
|
|
467
519
|
this.transport = null;
|
|
468
520
|
this._sessionId = null;
|
|
521
|
+
this.commandTransition = null;
|
|
522
|
+
this.setAvailableCommands([]);
|
|
469
523
|
this.terminals?.releaseAll();
|
|
470
524
|
this.terminals = null;
|
|
471
525
|
if (t) await t.stop();
|
|
@@ -607,7 +661,16 @@ export class AcpClient implements AgentClient {
|
|
|
607
661
|
this._configOptions = parseConfigOptions((update as Record<string, any>).configOptions);
|
|
608
662
|
}
|
|
609
663
|
if (kind === "available_commands_update") {
|
|
610
|
-
|
|
664
|
+
const commands = toAvailableCommands((update as Record<string, any>).availableCommands);
|
|
665
|
+
const sessionId = notification.sessionId || "";
|
|
666
|
+
if (this.commandTransition) {
|
|
667
|
+
// A session/new notification can precede its response, so the target id is not
|
|
668
|
+
// necessarily known yet. Buffer by wire session id and commit only the response's
|
|
669
|
+
// selected id when the transition finishes.
|
|
670
|
+
if (sessionId) this.commandTransition.bySession.set(sessionId, commands);
|
|
671
|
+
} else if (!sessionId || sessionId === this._sessionId) {
|
|
672
|
+
this.setAvailableCommands(commands);
|
|
673
|
+
}
|
|
611
674
|
}
|
|
612
675
|
|
|
613
676
|
if (!this.active) {
|
|
@@ -688,6 +751,56 @@ export class AcpClient implements AgentClient {
|
|
|
688
751
|
// Nothing recognizable to approve: refuse rather than guess. Guessing is the bug above.
|
|
689
752
|
return allow ? { outcome: "selected", optionId: allow.optionId } : { outcome: "cancelled" };
|
|
690
753
|
}
|
|
754
|
+
|
|
755
|
+
private beginCommandTransition(): void {
|
|
756
|
+
// Session operations are serialized by their callers. Preserve the last snapshot so
|
|
757
|
+
// a failed load/new can roll back without leaving an unrelated empty command palette.
|
|
758
|
+
this.commandTransition = { previous: this._availableCommands, bySession: new Map() };
|
|
759
|
+
this.setAvailableCommands([]);
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
private finishCommandTransition(sessionId: string): void {
|
|
763
|
+
const transition = this.commandTransition;
|
|
764
|
+
this.commandTransition = null;
|
|
765
|
+
this.setAvailableCommands(transition?.bySession.get(sessionId) ?? []);
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
private abortCommandTransition(): void {
|
|
769
|
+
const transition = this.commandTransition;
|
|
770
|
+
this.commandTransition = null;
|
|
771
|
+
if (transition) this.setAvailableCommands(transition.previous);
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
private setAvailableCommands(commands: readonly InternalSessionCommand[]): void {
|
|
775
|
+
if (sameAvailableCommands(this._availableCommands, commands)) return;
|
|
776
|
+
// Never expose the mutable transition scratch arrays used internally. Command
|
|
777
|
+
// objects come from toAvailableCommands() frozen; the copy makes the collection itself
|
|
778
|
+
// immutable as well, including the empty snapshots published between sessions.
|
|
779
|
+
const snapshot: readonly InternalSessionCommand[] = Object.freeze([...commands]);
|
|
780
|
+
this._availableCommands = snapshot;
|
|
781
|
+
for (const listener of [...this.availableCommandListeners]) {
|
|
782
|
+
try {
|
|
783
|
+
listener(snapshot);
|
|
784
|
+
} catch (err) {
|
|
785
|
+
this.log.warn("available_commands_listener_failed", { error: String(err) });
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
function sameAvailableCommands(
|
|
792
|
+
a: readonly InternalSessionCommand[],
|
|
793
|
+
b: readonly InternalSessionCommand[],
|
|
794
|
+
): boolean {
|
|
795
|
+
if (a.length !== b.length) return false;
|
|
796
|
+
return a.every((command, index) => {
|
|
797
|
+
const other = b[index];
|
|
798
|
+
return other != null &&
|
|
799
|
+
command.name === other.name &&
|
|
800
|
+
command.description === other.description &&
|
|
801
|
+
command.input?.kind === other.input?.kind &&
|
|
802
|
+
command.input?.hint === other.input?.hint;
|
|
803
|
+
});
|
|
691
804
|
}
|
|
692
805
|
|
|
693
806
|
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
|
+
}
|