@qlairoslabs/acp-client 0.11.0 → 0.12.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/CHANGELOG-consumer-fixes.md +55 -0
- package/CHANGELOG-operation-lifecycle.md +64 -0
- package/CONSUMER_GUIDE.md +311 -17
- package/MIGRATION-0.10-to-0.12.md +189 -0
- package/README.md +6 -3
- package/package.json +5 -2
- package/src/adapters.ts +3 -1
- package/src/agent/adoption/checkpoint-floor.ts +47 -0
- package/src/agent/adoption/index.ts +3 -1
- package/src/agent/adoption/replay.ts +15 -0
- package/src/agent/config.ts +4 -0
- package/src/agent/conversation-manager.ts +223 -153
- package/src/agent/error-record-writer.ts +77 -0
- package/src/agent/persisted-lifecycle.ts +152 -35
- package/src/agent/record-capture.ts +18 -18
- package/src/agent-adapter-registry.ts +2 -0
- package/src/agent-client.ts +9 -3
- package/src/agent-conversation-contracts.ts +6 -0
- package/src/agent-conversation-owner.ts +31 -6
- package/src/agent-conversation-presentation.ts +12 -1
- package/src/agent-conversation-queue.ts +3 -2
- package/src/agent-session.ts +537 -96
- package/src/agent.ts +46 -23
- package/src/audit/config.ts +4 -0
- package/src/audit/projection.ts +3 -0
- package/src/checkpointing/contracts.ts +28 -3
- package/src/checkpointing/persistence/sqlite-repository.ts +36 -8
- package/src/checkpointing/recovery.ts +9 -2
- package/src/checkpointing/strategy.ts +27 -2
- package/src/client.ts +120 -30
- package/src/controller.ts +116 -7
- package/src/degraded/pty-client.ts +25 -1
- package/src/identity/checkpoint-backed.ts +2 -2
- package/src/index.ts +17 -0
- package/src/internal-inference/config.ts +7 -0
- package/src/internal-inference/contracts.ts +3 -0
- package/src/internal-inference/coordination/handles.ts +11 -2
- package/src/internal-inference/coordination/manager.ts +20 -3
- package/src/internal-inference/index.ts +2 -0
- package/src/internal-inference/persistence/records.ts +3 -1
- package/src/internal-inference/persistence/sqlite-repository.ts +4 -1
- package/src/internal-inference/runtime/disposable-session-env.ts +84 -0
- package/src/internal-inference/runtime/harness-runtime.ts +19 -2
- package/src/media/acp.ts +118 -0
- package/src/media/capture.ts +15 -0
- package/src/media/content.ts +142 -0
- package/src/media/files.ts +28 -0
- package/src/media/parts.ts +145 -0
- package/src/media/pending.ts +51 -0
- package/src/media/redact.ts +14 -0
- package/src/media/store.ts +127 -0
- package/src/metering/provider.ts +8 -1
- package/src/operations/activity-tracker.ts +31 -0
- package/src/operations/contracts.ts +63 -0
- package/src/operations/errors.ts +31 -0
- package/src/operations/index.ts +6 -0
- package/src/operations/stale-policy.ts +51 -0
- package/src/operations/supervisor.ts +209 -0
- package/src/operations/timers.ts +12 -0
- package/src/out-of-band-messages.ts +49 -32
- package/src/persistence/audit-runtime.ts +14 -2
- package/src/persistence/backend.ts +108 -12
- package/src/persistence/error-records.ts +27 -0
- package/src/persistence/index.ts +8 -0
- package/src/persistence/presentation.ts +9 -1
- package/src/persistence/projection.ts +20 -0
- package/src/persistence/records.ts +45 -6
- package/src/persistence/sqlite-backend.ts +207 -16
- package/src/persistence/sqlite-conversation-records.ts +31 -4
- package/src/persistence/sqlite-files.ts +95 -0
- package/src/persistence/sqlite-media-store.ts +67 -0
- package/src/persistence/sqlite-schema.ts +146 -13
- package/src/persistence/state-runtime.ts +2 -0
- package/src/persistence/timeline-reconcile.ts +21 -4
- package/src/persistence/transcript-reader.ts +11 -4
- package/src/persistence/transcript-runtime.ts +105 -12
- package/src/repl/repl.ts +1 -1
- package/src/response.ts +40 -8
- package/src/steering/combine.ts +11 -4
- package/src/steering/contracts.ts +14 -4
- package/src/steering/controller.ts +96 -21
- package/src/steering/index.ts +1 -0
- package/src/transport/acp-transport.ts +18 -7
- package/src/types.ts +7 -0
- package/src/updates.ts +4 -4
package/src/client.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
// session/new|load) → prompt(). Capabilities and configOptions are populated by
|
|
6
6
|
// connect() so callers can inspect them BEFORE prompting.
|
|
7
7
|
|
|
8
|
+
import type { OutputListener, ProviderOutput } from "./operations/contracts.ts";
|
|
8
9
|
import { PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
|
|
9
10
|
import type * as schema from "@agentclientprotocol/sdk";
|
|
10
11
|
import type { Adapter } from "./adapters.ts";
|
|
@@ -37,6 +38,11 @@ import type {
|
|
|
37
38
|
ToolContent,
|
|
38
39
|
WireEntry,
|
|
39
40
|
} from "./types.ts";
|
|
41
|
+
import { promptParts } from "./media/parts.ts";
|
|
42
|
+
import { resolveParts } from "./media/store.ts";
|
|
43
|
+
import { assertPartCapabilities, attachmentParts, partsToAcp } from "./media/acp.ts";
|
|
44
|
+
import { redactMedia } from "./media/redact.ts";
|
|
45
|
+
import type { ClientPrompt } from "./agent-client.ts";
|
|
40
46
|
|
|
41
47
|
export interface AcpClientConfig {
|
|
42
48
|
/** How to launch the agent binary. */
|
|
@@ -52,6 +58,8 @@ export interface AcpClientConfig {
|
|
|
52
58
|
env?: Record<string, string>;
|
|
53
59
|
/** Workspace visible to the ACP target and sent in session requests. */
|
|
54
60
|
cwd?: string;
|
|
61
|
+
/** Additional workspace roots passed to ACP session creation and loading. */
|
|
62
|
+
additionalDirectories?: string[];
|
|
55
63
|
/** Resume this session id when startSession() is called. */
|
|
56
64
|
sessionId?: string;
|
|
57
65
|
/** Policy when config.sessionId cannot be loaded. Default "new" for compatibility. */
|
|
@@ -128,6 +136,7 @@ function resolveClientHandlers(
|
|
|
128
136
|
}
|
|
129
137
|
|
|
130
138
|
export interface StartSessionOptions {
|
|
139
|
+
additionalDirectories?: string[];
|
|
131
140
|
/** Resume this session. Defaults to config.sessionId. */
|
|
132
141
|
sessionId?: string;
|
|
133
142
|
/** What to do when the requested session cannot be loaded. Default config policy, then "new". */
|
|
@@ -165,7 +174,7 @@ export interface SwitchSessionOptions {
|
|
|
165
174
|
onUpdate?: (notification: unknown) => void;
|
|
166
175
|
}
|
|
167
176
|
|
|
168
|
-
interface QueueItem {
|
|
177
|
+
interface QueueItem extends ClientPrompt {
|
|
169
178
|
text: string;
|
|
170
179
|
handlers?: PromptHandlers;
|
|
171
180
|
attachments?: Attachment[];
|
|
@@ -196,6 +205,12 @@ export class AcpClient implements AgentClient {
|
|
|
196
205
|
private _availableCommands: readonly InternalSessionCommand[] = Object.freeze([]);
|
|
197
206
|
private readonly availableCommandListeners = new Set<AvailableCommandsListener>();
|
|
198
207
|
private readonly usageUpdateListeners = new Set<UsageUpdateListener>();
|
|
208
|
+
/** The stop in progress; later operations wait on it before reconnecting. */
|
|
209
|
+
private stopPromise: Promise<void> | null = null;
|
|
210
|
+
private readonly disconnectListeners = new Set<() => void>();
|
|
211
|
+
/** Answers `cancelled` to each permission request still waiting on the consumer's handler. */
|
|
212
|
+
private readonly pendingPermissions = new Set<() => void>();
|
|
213
|
+
private readonly outputListeners = new Set<OutputListener>();
|
|
199
214
|
/**
|
|
200
215
|
* Latest usage_update seen, replayed to a late subscriber.
|
|
201
216
|
*
|
|
@@ -289,12 +304,34 @@ export class AcpClient implements AgentClient {
|
|
|
289
304
|
}
|
|
290
305
|
return () => this.usageUpdateListeners.delete(listener);
|
|
291
306
|
}
|
|
307
|
+
subscribeDisconnect(listener: () => void): () => void {
|
|
308
|
+
this.disconnectListeners.add(listener);
|
|
309
|
+
return () => this.disconnectListeners.delete(listener);
|
|
310
|
+
}
|
|
311
|
+
subscribeOutput(listener: OutputListener): () => void {
|
|
312
|
+
this.outputListeners.add(listener);
|
|
313
|
+
return () => this.outputListeners.delete(listener);
|
|
314
|
+
}
|
|
315
|
+
private notifyDisconnected(): void {
|
|
316
|
+
for (const listener of [...this.disconnectListeners]) {
|
|
317
|
+
try { listener(); } catch (error) { this.log.warn("disconnect_listener_failed", { error: String(error) }); }
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
private cancelPendingPermissions(): void {
|
|
321
|
+
for (const cancel of [...this.pendingPermissions]) cancel();
|
|
322
|
+
}
|
|
323
|
+
private emitOutput(output: ProviderOutput): void {
|
|
324
|
+
for (const listener of [...this.outputListeners]) {
|
|
325
|
+
try { listener(output); }
|
|
326
|
+
catch (error) { this.log.warn("output_listener_failed", { error: String(error) }); }
|
|
327
|
+
}
|
|
328
|
+
}
|
|
292
329
|
get currentSessionId(): string | null {
|
|
293
330
|
return this._sessionId;
|
|
294
331
|
}
|
|
295
332
|
/** True once connect() has spawned + initialized (a session may not exist yet). */
|
|
296
333
|
get isConnected(): boolean {
|
|
297
|
-
return this.transport
|
|
334
|
+
return this.transport?.isConnected ?? false;
|
|
298
335
|
}
|
|
299
336
|
/** True once a session has been created or loaded. */
|
|
300
337
|
get hasSession(): boolean {
|
|
@@ -336,6 +373,7 @@ export class AcpClient implements AgentClient {
|
|
|
336
373
|
|
|
337
374
|
const transport = new AcpTransport({
|
|
338
375
|
launch,
|
|
376
|
+
onRequest: (sessionId) => this.emitOutput({ kind: "request", sessionId }),
|
|
339
377
|
onUpdate: (n) => this.handleUpdate(n),
|
|
340
378
|
onPermissionRequest: (p) => this.handlePermission(p),
|
|
341
379
|
onReadTextFile: readHandler,
|
|
@@ -346,7 +384,12 @@ export class AcpClient implements AgentClient {
|
|
|
346
384
|
this.log.debug("agent_stderr", { line });
|
|
347
385
|
this.authStderrSink?.(line);
|
|
348
386
|
},
|
|
387
|
+
onDisconnect: () => {
|
|
388
|
+
this.cancelPendingPermissions();
|
|
389
|
+
this.notifyDisconnected();
|
|
390
|
+
},
|
|
349
391
|
onCrash: (code) => {
|
|
392
|
+
this.cancelPendingPermissions();
|
|
350
393
|
this.terminals?.releaseAll();
|
|
351
394
|
this.terminals = null;
|
|
352
395
|
this.transport = null;
|
|
@@ -354,6 +397,7 @@ export class AcpClient implements AgentClient {
|
|
|
354
397
|
this.commandTransition = null;
|
|
355
398
|
this.setAvailableCommands([]);
|
|
356
399
|
this.log.error("process_exit", { code });
|
|
400
|
+
this.notifyDisconnected();
|
|
357
401
|
},
|
|
358
402
|
});
|
|
359
403
|
try {
|
|
@@ -397,6 +441,7 @@ export class AcpClient implements AgentClient {
|
|
|
397
441
|
async startSession(options: StartSessionOptions = {}): Promise<ConnectResult> {
|
|
398
442
|
const transport = this.requireTransport();
|
|
399
443
|
const mcpServers = options.mcpServers ?? [];
|
|
444
|
+
const additionalDirectories = options.additionalDirectories ?? this.config.additionalDirectories;
|
|
400
445
|
const cwd = this.config.cwd ?? process.cwd();
|
|
401
446
|
const resumeId = options.sessionId ?? this.config.sessionId;
|
|
402
447
|
const loadFailure = options.loadFailure ?? this.config.sessionLoadFailure ?? "new";
|
|
@@ -408,6 +453,7 @@ export class AcpClient implements AgentClient {
|
|
|
408
453
|
try {
|
|
409
454
|
const result = await this.loadSessionInternal(transport, resumeId, {
|
|
410
455
|
mcpServers,
|
|
456
|
+
additionalDirectories,
|
|
411
457
|
...(options.onReplayUpdate ? { onUpdate: options.onReplayUpdate } : {}),
|
|
412
458
|
});
|
|
413
459
|
sessionId = result.sessionId;
|
|
@@ -415,12 +461,12 @@ export class AcpClient implements AgentClient {
|
|
|
415
461
|
} catch (err) {
|
|
416
462
|
this.log.warn("session_load_failed", { sessionId: resumeId, error: String(err) });
|
|
417
463
|
if (loadFailure === "error") throw err;
|
|
418
|
-
sessionId = await this.newSessionInternal(transport, cwd, mcpServers);
|
|
464
|
+
sessionId = await this.newSessionInternal(transport, cwd, mcpServers, additionalDirectories);
|
|
419
465
|
}
|
|
420
466
|
} else if (resumeId && loadFailure === "error") {
|
|
421
467
|
throw new Error("agent does not advertise session/load for the requested internal session");
|
|
422
468
|
} else {
|
|
423
|
-
sessionId = await this.newSessionInternal(transport, cwd, mcpServers);
|
|
469
|
+
sessionId = await this.newSessionInternal(transport, cwd, mcpServers, additionalDirectories);
|
|
424
470
|
}
|
|
425
471
|
|
|
426
472
|
return { sessionId, resumed };
|
|
@@ -451,7 +497,7 @@ export class AcpClient implements AgentClient {
|
|
|
451
497
|
sessionId,
|
|
452
498
|
cwd: this.config.cwd ?? process.cwd(),
|
|
453
499
|
mcpServers: options.mcpServers ?? [],
|
|
454
|
-
additionalDirectories: options.additionalDirectories,
|
|
500
|
+
additionalDirectories: options.additionalDirectories ?? this.config.additionalDirectories,
|
|
455
501
|
} as schema.LoadSessionRequest);
|
|
456
502
|
} catch (err) {
|
|
457
503
|
this.abortCommandTransition();
|
|
@@ -488,7 +534,7 @@ export class AcpClient implements AgentClient {
|
|
|
488
534
|
sessionId,
|
|
489
535
|
cwd: this.config.cwd ?? process.cwd(),
|
|
490
536
|
mcpServers: options.mcpServers ?? [],
|
|
491
|
-
additionalDirectories: options.additionalDirectories,
|
|
537
|
+
additionalDirectories: options.additionalDirectories ?? this.config.additionalDirectories,
|
|
492
538
|
} as schema.ResumeSessionRequest);
|
|
493
539
|
} catch (err) {
|
|
494
540
|
this.abortCommandTransition();
|
|
@@ -537,7 +583,7 @@ export class AcpClient implements AgentClient {
|
|
|
537
583
|
sessionId,
|
|
538
584
|
cwd: this.config.cwd ?? process.cwd(),
|
|
539
585
|
mcpServers: options.mcpServers ?? [],
|
|
540
|
-
additionalDirectories: options.additionalDirectories,
|
|
586
|
+
additionalDirectories: options.additionalDirectories ?? this.config.additionalDirectories,
|
|
541
587
|
} as schema.ForkSessionRequest);
|
|
542
588
|
} catch (err) {
|
|
543
589
|
this.abortCommandTransition();
|
|
@@ -611,10 +657,13 @@ export class AcpClient implements AgentClient {
|
|
|
611
657
|
}
|
|
612
658
|
|
|
613
659
|
/** Force a brand-new session, ignoring config.sessionId. Useful after authenticating. */
|
|
614
|
-
async newSession(
|
|
660
|
+
async newSession(
|
|
661
|
+
options: { mcpServers?: schema.McpServer[]; additionalDirectories?: string[] } = {},
|
|
662
|
+
): Promise<ConnectResult> {
|
|
615
663
|
const transport = this.requireTransport();
|
|
616
664
|
const cwd = this.config.cwd ?? process.cwd();
|
|
617
|
-
const
|
|
665
|
+
const additionalDirectories = options.additionalDirectories ?? this.config.additionalDirectories;
|
|
666
|
+
const sessionId = await this.newSessionInternal(transport, cwd, options.mcpServers ?? [], additionalDirectories);
|
|
618
667
|
return { sessionId, resumed: false };
|
|
619
668
|
}
|
|
620
669
|
|
|
@@ -622,11 +671,16 @@ export class AcpClient implements AgentClient {
|
|
|
622
671
|
transport: AcpTransport,
|
|
623
672
|
cwd: string,
|
|
624
673
|
mcpServers: schema.McpServer[],
|
|
674
|
+
additionalDirectories?: string[],
|
|
625
675
|
): Promise<string> {
|
|
626
676
|
this.beginCommandTransition();
|
|
627
677
|
let res: schema.NewSessionResponse;
|
|
628
678
|
try {
|
|
629
|
-
res = await transport.newSession({
|
|
679
|
+
res = await transport.newSession({
|
|
680
|
+
cwd,
|
|
681
|
+
mcpServers,
|
|
682
|
+
...(additionalDirectories ? { additionalDirectories } : {}),
|
|
683
|
+
} as schema.NewSessionRequest);
|
|
630
684
|
} catch (err) {
|
|
631
685
|
this.abortCommandTransition();
|
|
632
686
|
throw err;
|
|
@@ -652,7 +706,9 @@ export class AcpClient implements AgentClient {
|
|
|
652
706
|
if (!this._sessionId) await this.startSession();
|
|
653
707
|
}
|
|
654
708
|
|
|
655
|
-
|
|
709
|
+
stop(): Promise<void> {
|
|
710
|
+
if (this.stopPromise) return this.stopPromise;
|
|
711
|
+
this.cancelPendingPermissions();
|
|
656
712
|
const t = this.transport;
|
|
657
713
|
this.transport = null;
|
|
658
714
|
this._sessionId = null;
|
|
@@ -660,8 +716,12 @@ export class AcpClient implements AgentClient {
|
|
|
660
716
|
this.setAvailableCommands([]);
|
|
661
717
|
this.terminals?.releaseAll();
|
|
662
718
|
this.terminals = null;
|
|
663
|
-
|
|
664
|
-
this.
|
|
719
|
+
const pending = t ? t.stop() : Promise.resolve();
|
|
720
|
+
this.stopPromise = pending.finally(() => {
|
|
721
|
+
this.stopPromise = null;
|
|
722
|
+
this.log.info("stopped", {});
|
|
723
|
+
});
|
|
724
|
+
return this.stopPromise;
|
|
665
725
|
}
|
|
666
726
|
|
|
667
727
|
/** Adapt the registry to the transport's async handler shape. */
|
|
@@ -684,12 +744,16 @@ export class AcpClient implements AgentClient {
|
|
|
684
744
|
// --- prompting ----------------------------------------------------------------
|
|
685
745
|
|
|
686
746
|
prompt(
|
|
687
|
-
|
|
747
|
+
input: string | ClientPrompt,
|
|
688
748
|
handlers?: PromptHandlers,
|
|
689
749
|
attachments?: Attachment[],
|
|
690
750
|
): Promise<PromptResult> {
|
|
751
|
+
// The positional form is the compatibility signature; the object form can carry parts.
|
|
752
|
+
const prompt: ClientPrompt = typeof input === "string"
|
|
753
|
+
? { text: input, handlers, attachments }
|
|
754
|
+
: { ...input, parts: promptParts(input) };
|
|
691
755
|
return new Promise<PromptResult>((resolve, reject) => {
|
|
692
|
-
this.queue.push({
|
|
756
|
+
this.queue.push({ ...prompt, text: prompt.text ?? "", resolve, reject });
|
|
693
757
|
void this.pump();
|
|
694
758
|
});
|
|
695
759
|
}
|
|
@@ -715,15 +779,13 @@ export class AcpClient implements AgentClient {
|
|
|
715
779
|
if (!this.transport) throw new NotConnectedError();
|
|
716
780
|
await this.ensureSession(); // lazily create a session on first prompt
|
|
717
781
|
|
|
718
|
-
const
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
} as schema.ContentBlock);
|
|
726
|
-
}
|
|
782
|
+
const capabilities = this._capabilities?.agent.promptCapabilities;
|
|
783
|
+
const parts = await resolveParts([
|
|
784
|
+
...(item.parts ?? (item.text ? [{ kind: "text" as const, text: item.text }] : [])),
|
|
785
|
+
...attachmentParts(item.attachments),
|
|
786
|
+
], { cwd: this.config.cwd ?? process.cwd(), capabilities });
|
|
787
|
+
assertPartCapabilities(parts, capabilities);
|
|
788
|
+
const contentBlocks = partsToAcp(parts);
|
|
727
789
|
if (contentBlocks.length === 0) contentBlocks.push({ type: "text", text: "" });
|
|
728
790
|
|
|
729
791
|
this.active = {
|
|
@@ -733,7 +795,7 @@ export class AcpClient implements AgentClient {
|
|
|
733
795
|
};
|
|
734
796
|
const t0 = Date.now();
|
|
735
797
|
this.log.debug("prompt_start", { chars: item.text.length });
|
|
736
|
-
this.log.debug("prompt_request", { sessionId: this._sessionId, prompt: contentBlocks });
|
|
798
|
+
this.log.debug("prompt_request", { sessionId: this._sessionId, prompt: redactMedia(contentBlocks) });
|
|
737
799
|
try {
|
|
738
800
|
const res = await this.transport.prompt({
|
|
739
801
|
sessionId: this._sessionId,
|
|
@@ -769,6 +831,7 @@ export class AcpClient implements AgentClient {
|
|
|
769
831
|
}
|
|
770
832
|
|
|
771
833
|
interrupt(options: InterruptOptions = {}): void {
|
|
834
|
+
this.cancelPendingPermissions();
|
|
772
835
|
if (options.clearQueue) {
|
|
773
836
|
const dropped = this.queue.splice(0);
|
|
774
837
|
for (const item of dropped) {
|
|
@@ -784,7 +847,10 @@ export class AcpClient implements AgentClient {
|
|
|
784
847
|
if (this.active && this.transport && this._sessionId) {
|
|
785
848
|
this.active.cancelled = true;
|
|
786
849
|
// ACP baseline: session/cancel. The in-flight prompt() then resolves naturally.
|
|
787
|
-
|
|
850
|
+
try {
|
|
851
|
+
void this.transport.cancel({ sessionId: this._sessionId } as schema.CancelNotification)
|
|
852
|
+
.catch((error) => this.log.warn("cancel_notification_failed", { error: String(error) }));
|
|
853
|
+
} catch (error) { this.log.warn("cancel_notification_failed", { error: String(error) }); }
|
|
788
854
|
}
|
|
789
855
|
}
|
|
790
856
|
|
|
@@ -808,6 +874,8 @@ export class AcpClient implements AgentClient {
|
|
|
808
874
|
// Raw protocol trace (logged even outside an active turn, e.g. session/load replay).
|
|
809
875
|
this.log.debug("session_update", { notification });
|
|
810
876
|
|
|
877
|
+
this.emitOutput({ kind: "update", sessionId: notification.sessionId ?? null,
|
|
878
|
+
activity: toActivityEvent(notification.update) ?? undefined });
|
|
811
879
|
const update = notification.update;
|
|
812
880
|
const kind = (update as Record<string, any>).sessionUpdate;
|
|
813
881
|
if (
|
|
@@ -859,6 +927,9 @@ export class AcpClient implements AgentClient {
|
|
|
859
927
|
this.active.handlers?.onChunk?.(chunk.text);
|
|
860
928
|
}
|
|
861
929
|
const activity = toActivityEvent(update);
|
|
930
|
+
// Text after a new tool call is a new message, even when the agent sends no message ids.
|
|
931
|
+
// Tool updates do not split: a running tool's output can arrive while the agent writes.
|
|
932
|
+
if (activity?.kind === "tool") this.active.response.closeMessage();
|
|
862
933
|
if (activity) this.active.handlers?.onActivity?.(this.enrich(activity));
|
|
863
934
|
}
|
|
864
935
|
|
|
@@ -891,11 +962,30 @@ export class AcpClient implements AgentClient {
|
|
|
891
962
|
const handler = this.active?.handlers?.onPermissionRequest;
|
|
892
963
|
const request = toPermissionRequest(params);
|
|
893
964
|
|
|
965
|
+
const abort = new AbortController();
|
|
966
|
+
let cancel!: () => void;
|
|
967
|
+
const cancelled = new Promise<PermissionOutcome>((resolve) => {
|
|
968
|
+
cancel = () => {
|
|
969
|
+
abort.abort();
|
|
970
|
+
resolve({ outcome: "cancelled" });
|
|
971
|
+
};
|
|
972
|
+
});
|
|
973
|
+
this.pendingPermissions.add(cancel);
|
|
974
|
+
this.emitOutput({ kind: "permission_started", sessionId: params.sessionId });
|
|
894
975
|
let outcome: PermissionOutcome;
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
outcome =
|
|
976
|
+
try {
|
|
977
|
+
// A stopped client may still read requests the dying process wrote; they belong to no turn.
|
|
978
|
+
if (this.active?.cancelled || !this.transport) cancel();
|
|
979
|
+
outcome = await Promise.race([
|
|
980
|
+
cancelled,
|
|
981
|
+
Promise.resolve().then(() => {
|
|
982
|
+
if (abort.signal.aborted) return { outcome: "cancelled" as const };
|
|
983
|
+
return handler ? handler(request, abort.signal) : this.defaultOutcome(request);
|
|
984
|
+
}),
|
|
985
|
+
]);
|
|
986
|
+
} finally {
|
|
987
|
+
this.pendingPermissions.delete(cancel);
|
|
988
|
+
this.emitOutput({ kind: "permission_ended", sessionId: params.sessionId });
|
|
899
989
|
}
|
|
900
990
|
|
|
901
991
|
this.log.debug("permission_response", { outcome });
|
package/src/controller.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { ForcedStopError } from "./operations/errors.ts";
|
|
2
|
+
import type { OperationLifecycleConfig, OutputListener } from "./operations/contracts.ts";
|
|
1
3
|
import {
|
|
2
4
|
AcpClient,
|
|
3
5
|
type AcpClientConfig,
|
|
@@ -22,6 +24,7 @@ import type {
|
|
|
22
24
|
WireEntry,
|
|
23
25
|
} from "./types.ts";
|
|
24
26
|
import { NotConnectedError } from "./errors.ts";
|
|
27
|
+
import type { ClientPrompt } from "./agent-client.ts";
|
|
25
28
|
|
|
26
29
|
const NO_AVAILABLE_COMMANDS: readonly InternalSessionCommand[] = Object.freeze([]);
|
|
27
30
|
|
|
@@ -33,7 +36,14 @@ const NO_AVAILABLE_COMMANDS: readonly InternalSessionCommand[] = Object.freeze([
|
|
|
33
36
|
*/
|
|
34
37
|
export type AgentMode = "normal" | "degraded";
|
|
35
38
|
|
|
39
|
+
/** The lifecycle surface both leaf clients (ACP and PTY) offer beyond `AgentClient`. */
|
|
40
|
+
type ObservableLeaf = AgentClient & {
|
|
41
|
+
readonly isConnected?: boolean;
|
|
42
|
+
subscribeOutput?(listener: OutputListener): () => void;
|
|
43
|
+
};
|
|
44
|
+
|
|
36
45
|
export interface AgentControllerConfig {
|
|
46
|
+
operationLifecycle?: OperationLifecycleConfig;
|
|
37
47
|
/** The single adapter this controller drives. Switching adapter = a new AgentSession. */
|
|
38
48
|
adapter: Adapter;
|
|
39
49
|
/** Stable id for the adapter (catalog/display, e.g. "codex"). */
|
|
@@ -47,6 +57,7 @@ export interface AgentControllerConfig {
|
|
|
47
57
|
/** @deprecated Use launcher and its exact spawnEnv. */
|
|
48
58
|
env?: Record<string, string>;
|
|
49
59
|
cwd?: string;
|
|
60
|
+
additionalDirectories?: string[];
|
|
50
61
|
/** Session id to load on start(). */
|
|
51
62
|
sessionId?: string;
|
|
52
63
|
/** Policy when sessionId cannot be loaded. Default "new" for compatibility. */
|
|
@@ -113,6 +124,10 @@ export class AgentController implements AgentClient {
|
|
|
113
124
|
// mode, a PtyClient in degraded mode. `acp` is the SAME object only in normal mode,
|
|
114
125
|
// typed for the rich ACP surface; it is null when degraded (that surface genuinely
|
|
115
126
|
// doesn't exist when screen-scraping).
|
|
127
|
+
private readonly forceStopListeners = new Set<() => void>();
|
|
128
|
+
private readonly connectionListeners = new Set<() => void>();
|
|
129
|
+
private detachDisconnect: (() => void) | null = null;
|
|
130
|
+
private stopping: Promise<void> = Promise.resolve();
|
|
116
131
|
private current: AgentClient | null = null;
|
|
117
132
|
private acp: AcpClient | null = null;
|
|
118
133
|
private mode: AgentMode;
|
|
@@ -123,12 +138,49 @@ export class AgentController implements AgentClient {
|
|
|
123
138
|
private readonly usageUpdateListeners = new Set<
|
|
124
139
|
(update: unknown, sessionId: string | null) => void
|
|
125
140
|
>();
|
|
141
|
+
private readonly outputListeners = new Set<OutputListener>();
|
|
142
|
+
private detachOutput: (() => void) | null = null;
|
|
126
143
|
private detachUsageUpdates: (() => void) | null = null;
|
|
127
144
|
|
|
128
145
|
constructor(private readonly config: AgentControllerConfig) {
|
|
129
146
|
this.mode = config.mode ?? "normal";
|
|
130
147
|
}
|
|
131
148
|
|
|
149
|
+
get isConnected(): boolean {
|
|
150
|
+
return this.current !== null && ((this.current as ObservableLeaf).isConnected ?? true);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
subscribeConnection(listener: () => void): () => void {
|
|
154
|
+
this.connectionListeners.add(listener);
|
|
155
|
+
return () => this.connectionListeners.delete(listener);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
private connectionChanged(): void {
|
|
159
|
+
for (const listener of [...this.connectionListeners]) {
|
|
160
|
+
try {
|
|
161
|
+
listener();
|
|
162
|
+
} catch (error) {
|
|
163
|
+
this.config.logger?.warn("connection_listener_failed", { error: String(error) });
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async reconnect(sessionId: string): Promise<ConnectResult> {
|
|
169
|
+
await this.stopping;
|
|
170
|
+
await this.stop();
|
|
171
|
+
const brought = await this.bringUp(this.mode, sessionId, undefined, "error");
|
|
172
|
+
this.current = brought.client;
|
|
173
|
+
this.acp = brought.acp;
|
|
174
|
+
this.attachAvailableCommandSource();
|
|
175
|
+
if (!brought.result.resumed || brought.result.sessionId !== sessionId) {
|
|
176
|
+
await this.stop();
|
|
177
|
+
throw new Error("provider did not load the requested session");
|
|
178
|
+
}
|
|
179
|
+
return brought.result;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
get cancelGraceMs(): number | undefined { return this.config.adapter.cancelGraceMs; }
|
|
183
|
+
|
|
132
184
|
get currentAdapterId(): string {
|
|
133
185
|
return this.config.adapterId;
|
|
134
186
|
}
|
|
@@ -188,7 +240,14 @@ export class AgentController implements AgentClient {
|
|
|
188
240
|
return () => this.usageUpdateListeners.delete(listener);
|
|
189
241
|
}
|
|
190
242
|
|
|
243
|
+
subscribeOutput(listener: OutputListener): () => void {
|
|
244
|
+
this.outputListeners.add(listener);
|
|
245
|
+
return () => this.outputListeners.delete(listener);
|
|
246
|
+
}
|
|
247
|
+
|
|
191
248
|
async start(onProgress?: (event: AgentControllerStartEvent) => void): Promise<ConnectResult> {
|
|
249
|
+
await this.stopping;
|
|
250
|
+
if (this.current && !this.isConnected) await this.stop();
|
|
192
251
|
if (this.current) {
|
|
193
252
|
return { sessionId: this.currentSessionId ?? "", resumed: this.acp?.hasSession ?? false };
|
|
194
253
|
}
|
|
@@ -201,6 +260,8 @@ export class AgentController implements AgentClient {
|
|
|
201
260
|
|
|
202
261
|
/** Explicitly create a fresh provider thread, ignoring any startup load target. */
|
|
203
262
|
async startFresh(onProgress?: (event: AgentControllerStartEvent) => void): Promise<ConnectResult> {
|
|
263
|
+
await this.stopping;
|
|
264
|
+
if (this.current && !this.isConnected) await this.stop();
|
|
204
265
|
if (this.current) {
|
|
205
266
|
if (!this.acp) throw new Error("fresh provider sessions require ACP normal mode");
|
|
206
267
|
return await this.newSession();
|
|
@@ -213,11 +274,26 @@ export class AgentController implements AgentClient {
|
|
|
213
274
|
}
|
|
214
275
|
|
|
215
276
|
prompt(
|
|
216
|
-
|
|
277
|
+
input: string | ClientPrompt,
|
|
217
278
|
handlers?: PromptHandlers,
|
|
218
279
|
attachments?: Attachment[],
|
|
219
280
|
): Promise<PromptResult> {
|
|
220
|
-
|
|
281
|
+
const prompt: ClientPrompt = typeof input === "string" ? { text: input, handlers, attachments } : input;
|
|
282
|
+
const current = this.requireCurrent();
|
|
283
|
+
let forced!: () => void;
|
|
284
|
+
const interrupted = new Promise<never>((_resolve, reject) => {
|
|
285
|
+
forced = () => reject(new ForcedStopError());
|
|
286
|
+
this.forceStopListeners.add(forced);
|
|
287
|
+
});
|
|
288
|
+
return Promise.race([current.prompt(prompt), interrupted])
|
|
289
|
+
.finally(() => this.forceStopListeners.delete(forced));
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
cancel(): void { this.current?.interrupt(); }
|
|
293
|
+
|
|
294
|
+
forceStop(): Promise<void> {
|
|
295
|
+
for (const force of [...this.forceStopListeners]) force();
|
|
296
|
+
return this.stop();
|
|
221
297
|
}
|
|
222
298
|
|
|
223
299
|
interrupt(options?: InterruptOptions): void {
|
|
@@ -257,12 +333,23 @@ export class AgentController implements AgentClient {
|
|
|
257
333
|
const client = this.current;
|
|
258
334
|
this.current = null;
|
|
259
335
|
this.acp = null;
|
|
336
|
+
this.detachDisconnect?.();
|
|
337
|
+
this.detachDisconnect = null;
|
|
338
|
+
this.connectionChanged();
|
|
260
339
|
this.detachAvailableCommands?.();
|
|
261
340
|
this.detachAvailableCommands = null;
|
|
262
341
|
this.detachUsageUpdates?.();
|
|
263
342
|
this.detachUsageUpdates = null;
|
|
343
|
+
this.detachOutput?.();
|
|
344
|
+
this.detachOutput = null;
|
|
264
345
|
this.emitAvailableCommands(NO_AVAILABLE_COMMANDS);
|
|
265
|
-
if (client)
|
|
346
|
+
if (client) {
|
|
347
|
+
const pending = client.stop();
|
|
348
|
+
this.stopping = pending.then(() => {}, () => {});
|
|
349
|
+
await pending;
|
|
350
|
+
} else {
|
|
351
|
+
await this.stopping;
|
|
352
|
+
}
|
|
266
353
|
}
|
|
267
354
|
|
|
268
355
|
/**
|
|
@@ -293,9 +380,12 @@ export class AgentController implements AgentClient {
|
|
|
293
380
|
}
|
|
294
381
|
|
|
295
382
|
/** Force a fresh session (e.g. after /login). mcpServers defaults to config.mcpServers. */
|
|
296
|
-
newSession(
|
|
383
|
+
newSession(
|
|
384
|
+
options: { mcpServers?: schema.McpServer[]; additionalDirectories?: string[] } = {},
|
|
385
|
+
): Promise<ConnectResult> {
|
|
297
386
|
return this.requireAcp().newSession({
|
|
298
387
|
mcpServers: options.mcpServers ?? this.config.mcpServers,
|
|
388
|
+
additionalDirectories: options.additionalDirectories ?? this.config.additionalDirectories,
|
|
299
389
|
});
|
|
300
390
|
}
|
|
301
391
|
|
|
@@ -307,6 +397,7 @@ export class AgentController implements AgentClient {
|
|
|
307
397
|
return this.requireAcp().loadSession(sessionId, {
|
|
308
398
|
...options,
|
|
309
399
|
mcpServers: options.mcpServers ?? this.config.mcpServers,
|
|
400
|
+
additionalDirectories: options.additionalDirectories ?? this.config.additionalDirectories,
|
|
310
401
|
});
|
|
311
402
|
}
|
|
312
403
|
|
|
@@ -314,6 +405,7 @@ export class AgentController implements AgentClient {
|
|
|
314
405
|
return this.requireAcp().resumeSession(sessionId, {
|
|
315
406
|
...options,
|
|
316
407
|
mcpServers: options.mcpServers ?? this.config.mcpServers,
|
|
408
|
+
additionalDirectories: options.additionalDirectories ?? this.config.additionalDirectories,
|
|
317
409
|
});
|
|
318
410
|
}
|
|
319
411
|
|
|
@@ -321,6 +413,7 @@ export class AgentController implements AgentClient {
|
|
|
321
413
|
return this.requireAcp().forkSession(sessionId, {
|
|
322
414
|
...options,
|
|
323
415
|
mcpServers: options.mcpServers ?? this.config.mcpServers,
|
|
416
|
+
additionalDirectories: options.additionalDirectories ?? this.config.additionalDirectories,
|
|
324
417
|
});
|
|
325
418
|
}
|
|
326
419
|
|
|
@@ -459,6 +552,7 @@ export class AgentController implements AgentClient {
|
|
|
459
552
|
mode: AgentMode,
|
|
460
553
|
sessionId?: string,
|
|
461
554
|
onProgress?: (event: AgentControllerStartEvent) => void,
|
|
555
|
+
loadFailure = this.config.sessionLoadFailure,
|
|
462
556
|
): Promise<{ client: AgentClient; acp: AcpClient | null; result: ConnectResult }> {
|
|
463
557
|
const adapter = this.config.adapter;
|
|
464
558
|
if (mode === "degraded") {
|
|
@@ -486,8 +580,9 @@ export class AgentController implements AgentClient {
|
|
|
486
580
|
execPrefix: this.config.execPrefix,
|
|
487
581
|
env: this.config.env,
|
|
488
582
|
cwd: this.config.cwd,
|
|
583
|
+
additionalDirectories: this.config.additionalDirectories,
|
|
489
584
|
sessionId,
|
|
490
|
-
sessionLoadFailure:
|
|
585
|
+
sessionLoadFailure: loadFailure,
|
|
491
586
|
defaultPermission: this.config.defaultPermission,
|
|
492
587
|
clientInfo: this.config.clientInfo,
|
|
493
588
|
clientCapabilities: this.config.clientCapabilities,
|
|
@@ -509,11 +604,12 @@ export class AgentController implements AgentClient {
|
|
|
509
604
|
try {
|
|
510
605
|
result = await client.startSession({
|
|
511
606
|
mcpServers: this.config.mcpServers,
|
|
512
|
-
|
|
607
|
+
additionalDirectories: this.config.additionalDirectories,
|
|
608
|
+
loadFailure: loadFailure,
|
|
513
609
|
...(this.config.onSessionReplay ? { onReplayUpdate: this.config.onSessionReplay } : {}),
|
|
514
610
|
});
|
|
515
611
|
} catch (err) {
|
|
516
|
-
if (sessionId &&
|
|
612
|
+
if (sessionId && loadFailure === "error") {
|
|
517
613
|
await client.stop();
|
|
518
614
|
throw err;
|
|
519
615
|
}
|
|
@@ -558,6 +654,19 @@ export class AgentController implements AgentClient {
|
|
|
558
654
|
}
|
|
559
655
|
|
|
560
656
|
private attachAvailableCommandSource(): void {
|
|
657
|
+
this.detachDisconnect?.();
|
|
658
|
+
this.detachDisconnect = this.acp?.subscribeDisconnect(() => this.connectionChanged()) ?? null;
|
|
659
|
+
this.connectionChanged();
|
|
660
|
+
this.detachOutput?.();
|
|
661
|
+
this.detachOutput = (this.current as ObservableLeaf | null)?.subscribeOutput?.((output) => {
|
|
662
|
+
for (const listener of [...this.outputListeners]) {
|
|
663
|
+
try {
|
|
664
|
+
listener(output);
|
|
665
|
+
} catch (error) {
|
|
666
|
+
this.config.logger?.warn("controller_output_listener_failed", { error: String(error) });
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
}) ?? null;
|
|
561
670
|
this.detachAvailableCommands?.();
|
|
562
671
|
this.detachAvailableCommands = this.acp?.subscribeAvailableCommands((commands) =>
|
|
563
672
|
this.emitAvailableCommands(commands)) ?? null;
|