@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/agent-session.ts
CHANGED
|
@@ -27,7 +27,7 @@ import {
|
|
|
27
27
|
} from "./transcript.ts";
|
|
28
28
|
import type {
|
|
29
29
|
ActivityEvent,
|
|
30
|
-
|
|
30
|
+
InternalSessionCommand,
|
|
31
31
|
Attachment,
|
|
32
32
|
PromptHandlers,
|
|
33
33
|
PromptResult,
|
|
@@ -35,7 +35,9 @@ import type {
|
|
|
35
35
|
WireEntry,
|
|
36
36
|
} from "./types.ts";
|
|
37
37
|
|
|
38
|
-
interface
|
|
38
|
+
interface PromptQueueItem {
|
|
39
|
+
kind: "prompt";
|
|
40
|
+
turnId: string;
|
|
39
41
|
text: string;
|
|
40
42
|
handlers?: PromptHandlers;
|
|
41
43
|
attachments?: Attachment[];
|
|
@@ -43,6 +45,77 @@ interface QueueItem {
|
|
|
43
45
|
reject: (e: unknown) => void;
|
|
44
46
|
}
|
|
45
47
|
|
|
48
|
+
interface HandoffQueueItem {
|
|
49
|
+
kind: "handoff";
|
|
50
|
+
handoffId: string;
|
|
51
|
+
options: HandoffOptions;
|
|
52
|
+
resolve: (result: HandoffResult) => void;
|
|
53
|
+
reject: (error: unknown) => void;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
type QueueItem = PromptQueueItem | HandoffQueueItem;
|
|
57
|
+
|
|
58
|
+
/** What the stable logical session is doing right now. */
|
|
59
|
+
export type AgentSessionPhase = "idle" | "prompting" | "handoff" | "stopped";
|
|
60
|
+
|
|
61
|
+
/** Authoritative, immutable point-in-time state for orchestration consumers. */
|
|
62
|
+
export interface AgentSessionState {
|
|
63
|
+
readonly phase: AgentSessionPhase;
|
|
64
|
+
/** True only while an operation is executing; queued work is reported separately. */
|
|
65
|
+
readonly isBusy: boolean;
|
|
66
|
+
/** Operations waiting behind the active one. Does not count the active operation. */
|
|
67
|
+
readonly queuedOperationCount: number;
|
|
68
|
+
readonly agentSessionId: string;
|
|
69
|
+
readonly internalSessionId: string | null;
|
|
70
|
+
readonly adapterId: string;
|
|
71
|
+
readonly mode: AgentMode;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface HandoffOptions {
|
|
75
|
+
/** Portable continuation context. When omitted, the current thread generates it. */
|
|
76
|
+
readonly summary?: string;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface HandoffResult {
|
|
80
|
+
readonly handoffId: string;
|
|
81
|
+
readonly agentSessionId: string;
|
|
82
|
+
readonly fromInternalSessionId: string | null;
|
|
83
|
+
readonly toInternalSessionId: string;
|
|
84
|
+
readonly summary: string;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Session-owned lifecycle events. Harness activity remains in PromptHandlers.onActivity. */
|
|
88
|
+
export type AgentSessionEvent =
|
|
89
|
+
| { kind: "state_changed"; state: AgentSessionState }
|
|
90
|
+
| { kind: "turn_started"; turnId: string }
|
|
91
|
+
| { kind: "turn_completed"; turnId: string; result: PromptResult }
|
|
92
|
+
| { kind: "turn_failed"; turnId: string; error: string }
|
|
93
|
+
/** The active ACP harness changed the slash commands it advertises. */
|
|
94
|
+
| { kind: "internal_session_commands_changed"; commands: readonly InternalSessionCommand[] }
|
|
95
|
+
| {
|
|
96
|
+
kind: "handoff_started";
|
|
97
|
+
handoffId: string;
|
|
98
|
+
fromInternalSessionId: string | null;
|
|
99
|
+
}
|
|
100
|
+
| { kind: "handoff_completed"; result: HandoffResult }
|
|
101
|
+
| {
|
|
102
|
+
kind: "handoff_failed";
|
|
103
|
+
handoffId: string;
|
|
104
|
+
fromInternalSessionId: string | null;
|
|
105
|
+
toInternalSessionId?: string;
|
|
106
|
+
error: string;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
/** Ordered envelope delivered to every AgentSession subscriber. */
|
|
110
|
+
export interface AgentSessionNotification {
|
|
111
|
+
readonly seq: number;
|
|
112
|
+
readonly ts: number;
|
|
113
|
+
readonly agentSessionId: string;
|
|
114
|
+
readonly event: AgentSessionEvent;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export type AgentSessionListener = (notification: AgentSessionNotification) => void;
|
|
118
|
+
|
|
46
119
|
/** What to record when `transcriptActivity` is on. */
|
|
47
120
|
export interface TranscriptActivityConfig {
|
|
48
121
|
/**
|
|
@@ -85,6 +158,31 @@ const DEFAULT_ACTIVITY_KINDS: Array<ActivityEvent["kind"]> = [
|
|
|
85
158
|
"unknown",
|
|
86
159
|
];
|
|
87
160
|
|
|
161
|
+
const HANDOFF_SUMMARY_PROMPT = [
|
|
162
|
+
"Create portable continuation context for a new agent thread.",
|
|
163
|
+
"Summarize the objective, decisions, completed work, current state, important files or identifiers,",
|
|
164
|
+
"and concrete next steps. Preserve unresolved risks and constraints. Return only the continuation context.",
|
|
165
|
+
].join(" ");
|
|
166
|
+
|
|
167
|
+
function continuationPrompt(summary: string): string {
|
|
168
|
+
return [
|
|
169
|
+
"Continue this conversation using the following portable continuation context.",
|
|
170
|
+
"Treat it as prior context, not as a new user request. Confirm internally and continue from this state.",
|
|
171
|
+
"",
|
|
172
|
+
summary,
|
|
173
|
+
].join("\n");
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Explicit selection of the provider thread backing a newly opened AgentSession. */
|
|
177
|
+
export type ProviderSession =
|
|
178
|
+
| { readonly kind: "new" }
|
|
179
|
+
| {
|
|
180
|
+
readonly kind: "load";
|
|
181
|
+
readonly internalSessionId: string;
|
|
182
|
+
/** Default "error": never silently replace a requested thread. */
|
|
183
|
+
readonly onFailure?: "error" | "new";
|
|
184
|
+
};
|
|
185
|
+
|
|
88
186
|
export interface AgentSessionConfig {
|
|
89
187
|
/** The resolved adapter this conversation talks to. */
|
|
90
188
|
adapter: Adapter;
|
|
@@ -106,9 +204,15 @@ export interface AgentSessionConfig {
|
|
|
106
204
|
wire?: (entry: WireEntry) => void;
|
|
107
205
|
/** Optional catalog. When present, the session records itself here. */
|
|
108
206
|
sessions?: SessionManager;
|
|
109
|
-
/**
|
|
207
|
+
/**
|
|
208
|
+
* Absolute path to an append-only transcript file. This selects history storage only;
|
|
209
|
+
* file existence never selects the provider thread. Omitted means no transcript.
|
|
210
|
+
*/
|
|
110
211
|
transcriptPath?: string;
|
|
111
|
-
/**
|
|
212
|
+
/**
|
|
213
|
+
* Directory for `<encoded-agentSessionId>.jsonl`. This selects history storage only;
|
|
214
|
+
* the directory is not a session catalog and is not scanned during creation.
|
|
215
|
+
*/
|
|
112
216
|
transcriptDir?: string;
|
|
113
217
|
/**
|
|
114
218
|
* Also record activity (thinking, tool calls and their output, plans) as `t:"activity"`
|
|
@@ -121,9 +225,14 @@ export interface AgentSessionConfig {
|
|
|
121
225
|
* `recordId`. `true` selects the defaults below.
|
|
122
226
|
*/
|
|
123
227
|
transcriptActivity?: boolean | TranscriptActivityConfig;
|
|
124
|
-
/**
|
|
228
|
+
/** Stable logical identity. Minted if omitted; always available on the created object. */
|
|
125
229
|
agentSessionId?: string;
|
|
126
|
-
/**
|
|
230
|
+
/** Provider-thread startup intent. Default `{ kind: "new" }`. */
|
|
231
|
+
providerSession?: ProviderSession;
|
|
232
|
+
/**
|
|
233
|
+
* @deprecated Use `providerSession: { kind: "load", internalSessionId, onFailure }`.
|
|
234
|
+
* Retains the historical fallback-to-new behavior for compatibility.
|
|
235
|
+
*/
|
|
127
236
|
internalSessionId?: string;
|
|
128
237
|
title?: string;
|
|
129
238
|
}
|
|
@@ -135,7 +244,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
135
244
|
|
|
136
245
|
private readonly controller: AgentController;
|
|
137
246
|
private readonly sessions?: SessionManager;
|
|
138
|
-
private readonly
|
|
247
|
+
private readonly _transcriptPath?: string;
|
|
139
248
|
private readonly transcriptActivity: boolean;
|
|
140
249
|
private readonly activityKinds: Set<string>;
|
|
141
250
|
private readonly activityRawOutput: boolean;
|
|
@@ -151,6 +260,10 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
151
260
|
private transcriptWrite: Promise<void> = Promise.resolve();
|
|
152
261
|
private queue: QueueItem[] = [];
|
|
153
262
|
private pumping = false;
|
|
263
|
+
private phase: AgentSessionPhase = "idle";
|
|
264
|
+
private notificationSeq = 0;
|
|
265
|
+
private readonly listeners = new Set<AgentSessionListener>();
|
|
266
|
+
private lastStateKey = "";
|
|
154
267
|
private _internalSessionId: string | null;
|
|
155
268
|
private _mode: AgentMode;
|
|
156
269
|
private _cwd?: string;
|
|
@@ -160,10 +273,32 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
160
273
|
if (config.transcriptPath && config.transcriptDir) {
|
|
161
274
|
throw new Error("AgentSessionConfig cannot specify both transcriptPath and transcriptDir");
|
|
162
275
|
}
|
|
276
|
+
if (config.providerSession && config.internalSessionId !== undefined) {
|
|
277
|
+
throw new Error("AgentSessionConfig cannot specify both providerSession and internalSessionId");
|
|
278
|
+
}
|
|
279
|
+
if (config.agentSessionId !== undefined && !config.agentSessionId.trim()) {
|
|
280
|
+
throw new Error("AgentSessionConfig.agentSessionId cannot be blank");
|
|
281
|
+
}
|
|
282
|
+
const providerSession: ProviderSession = config.providerSession ??
|
|
283
|
+
(config.internalSessionId !== undefined
|
|
284
|
+
? { kind: "load", internalSessionId: config.internalSessionId, onFailure: "new" }
|
|
285
|
+
: { kind: "new" });
|
|
286
|
+
if (providerSession.kind === "load" && !providerSession.internalSessionId.trim()) {
|
|
287
|
+
throw new Error("providerSession.internalSessionId cannot be blank");
|
|
288
|
+
}
|
|
289
|
+
if ((config.mode ?? "normal") === "degraded" && providerSession.kind === "load") {
|
|
290
|
+
throw new Error("providerSession.kind=load requires ACP (normal) mode");
|
|
291
|
+
}
|
|
292
|
+
const requestedInternalSessionId = providerSession.kind === "load"
|
|
293
|
+
? providerSession.internalSessionId
|
|
294
|
+
: undefined;
|
|
295
|
+
|
|
296
|
+
// IDs are opaque provider/consumer values. Validate blankness above, but never
|
|
297
|
+
// normalize a nonblank identifier and accidentally select a different session.
|
|
163
298
|
this.agentSessionId = config.agentSessionId ?? crypto.randomUUID();
|
|
164
299
|
this.adapterId = config.adapterId;
|
|
165
300
|
this.sessions = config.sessions;
|
|
166
|
-
this.
|
|
301
|
+
this._transcriptPath =
|
|
167
302
|
config.transcriptPath ??
|
|
168
303
|
(config.transcriptDir
|
|
169
304
|
? join(config.transcriptDir, `${encodeURIComponent(this.agentSessionId)}.jsonl`)
|
|
@@ -180,7 +315,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
180
315
|
this._mode = config.mode ?? "normal";
|
|
181
316
|
this._cwd = config.cwd;
|
|
182
317
|
this._title = config.title;
|
|
183
|
-
this._internalSessionId =
|
|
318
|
+
this._internalSessionId = requestedInternalSessionId ?? null;
|
|
184
319
|
this.controller = new AgentController({
|
|
185
320
|
adapter: config.adapter,
|
|
186
321
|
adapterId: config.adapterId,
|
|
@@ -188,7 +323,10 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
188
323
|
execPrefix: config.execPrefix,
|
|
189
324
|
env: config.env,
|
|
190
325
|
cwd: config.cwd,
|
|
191
|
-
sessionId:
|
|
326
|
+
sessionId: requestedInternalSessionId,
|
|
327
|
+
sessionLoadFailure: providerSession.kind === "load"
|
|
328
|
+
? providerSession.onFailure ?? "error"
|
|
329
|
+
: undefined,
|
|
192
330
|
mcpServers: config.mcpServers,
|
|
193
331
|
defaultPermission: config.defaultPermission,
|
|
194
332
|
clientInfo: config.clientInfo,
|
|
@@ -196,12 +334,16 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
196
334
|
logger: config.logger,
|
|
197
335
|
wire: config.wire,
|
|
198
336
|
});
|
|
337
|
+
this.controller.subscribeAvailableCommands((commands) => {
|
|
338
|
+
this.emit({ kind: "internal_session_commands_changed", commands });
|
|
339
|
+
});
|
|
199
340
|
}
|
|
200
341
|
|
|
201
342
|
/**
|
|
202
|
-
*
|
|
203
|
-
* `
|
|
204
|
-
*
|
|
343
|
+
* Open a logical conversation. `agentSessionId` selects stable identity;
|
|
344
|
+
* `providerSession` independently selects a new or existing provider thread; transcript
|
|
345
|
+
* options independently select history storage. No catalog or transcript is read
|
|
346
|
+
* implicitly. Consumers compose a catalog record back into this method when reopening.
|
|
205
347
|
*/
|
|
206
348
|
static async create(config: AgentSessionConfig): Promise<AgentSession> {
|
|
207
349
|
const session = new AgentSession(config);
|
|
@@ -236,6 +378,34 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
236
378
|
get title(): string | undefined {
|
|
237
379
|
return this._title;
|
|
238
380
|
}
|
|
381
|
+
/** Resolved history destination, configured directly or derived from transcriptDir. */
|
|
382
|
+
get transcriptPath(): string | undefined {
|
|
383
|
+
return this._transcriptPath;
|
|
384
|
+
}
|
|
385
|
+
/** Immutable current state. Late subscribers read this before listening for deltas. */
|
|
386
|
+
get state(): AgentSessionState {
|
|
387
|
+
return Object.freeze({
|
|
388
|
+
phase: this.phase,
|
|
389
|
+
isBusy: this.isBusy,
|
|
390
|
+
queuedOperationCount: this.queuedOperationCount,
|
|
391
|
+
agentSessionId: this.agentSessionId,
|
|
392
|
+
internalSessionId: this._internalSessionId,
|
|
393
|
+
adapterId: this.adapterId,
|
|
394
|
+
mode: this._mode,
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
/** True while one operation is executing. Queued work is exposed independently. */
|
|
398
|
+
get isBusy(): boolean {
|
|
399
|
+
return this.phase === "prompting" || this.phase === "handoff";
|
|
400
|
+
}
|
|
401
|
+
get queuedOperationCount(): number {
|
|
402
|
+
return this.queue.length;
|
|
403
|
+
}
|
|
404
|
+
/** Subscribe to future lifecycle changes. The current snapshot is available via state. */
|
|
405
|
+
subscribe(listener: AgentSessionListener): () => void {
|
|
406
|
+
this.listeners.add(listener);
|
|
407
|
+
return () => this.listeners.delete(listener);
|
|
408
|
+
}
|
|
239
409
|
/** Escape hatch to the live control plane (config, caps, getCommands, login, …). */
|
|
240
410
|
get connection(): AgentController {
|
|
241
411
|
return this.controller;
|
|
@@ -248,7 +418,67 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
248
418
|
attachments?: Attachment[],
|
|
249
419
|
): Promise<PromptResult> {
|
|
250
420
|
return new Promise<PromptResult>((resolve, reject) => {
|
|
251
|
-
this.
|
|
421
|
+
if (this.phase === "stopped") {
|
|
422
|
+
reject(new Error("AgentSession is stopped"));
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
this.queue.push({
|
|
426
|
+
kind: "prompt",
|
|
427
|
+
turnId: this.mintTurnId(),
|
|
428
|
+
text,
|
|
429
|
+
handlers,
|
|
430
|
+
attachments,
|
|
431
|
+
resolve,
|
|
432
|
+
reject,
|
|
433
|
+
});
|
|
434
|
+
this.emitStateIfChanged();
|
|
435
|
+
void this.pump();
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* Execute one command advertised by the active ACP harness. ACP represents slash
|
|
441
|
+
* commands as ordinary prompt text; this method makes that intentional and keeps the
|
|
442
|
+
* operation in the same queue, lifecycle events, and transcript as every other turn.
|
|
443
|
+
* Advertisement is discoverability, not an allow-list: a harness may accept commands
|
|
444
|
+
* that it did not advertise yet.
|
|
445
|
+
*/
|
|
446
|
+
executeInternalSessionCommand(
|
|
447
|
+
name: string,
|
|
448
|
+
input?: string,
|
|
449
|
+
handlers?: PromptHandlers,
|
|
450
|
+
): Promise<PromptResult> {
|
|
451
|
+
const command = name.trim();
|
|
452
|
+
if (!command || command.startsWith("/") || /\s/.test(command)) {
|
|
453
|
+
return Promise.reject(
|
|
454
|
+
new Error("internal session command name must be non-empty, contain no whitespace, and omit the leading slash"),
|
|
455
|
+
);
|
|
456
|
+
}
|
|
457
|
+
const suffix = input == null || input.length === 0 ? "" : ` ${input}`;
|
|
458
|
+
return this.prompt(`/${command}${suffix}`, handlers);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* Replace the underlying ACP thread while preserving this logical AgentSession object
|
|
463
|
+
* and id. The operation is serialized with prompts, so consumers never have to
|
|
464
|
+
* coordinate a handoff against in-flight work themselves.
|
|
465
|
+
*/
|
|
466
|
+
handoff(options: HandoffOptions = {}): Promise<HandoffResult> {
|
|
467
|
+
return new Promise<HandoffResult>((resolve, reject) => {
|
|
468
|
+
if (this.phase === "stopped") {
|
|
469
|
+
reject(new Error("AgentSession is stopped"));
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
this.queue.push({
|
|
473
|
+
kind: "handoff",
|
|
474
|
+
handoffId: this.mintOperationId(),
|
|
475
|
+
// A queued operation owns its arguments. Do not let a caller mutate the object
|
|
476
|
+
// while it waits behind an active prompt and silently change the handoff.
|
|
477
|
+
options: Object.freeze({ ...options }),
|
|
478
|
+
resolve,
|
|
479
|
+
reject,
|
|
480
|
+
});
|
|
481
|
+
this.emitStateIfChanged();
|
|
252
482
|
void this.pump();
|
|
253
483
|
});
|
|
254
484
|
}
|
|
@@ -259,19 +489,146 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
259
489
|
try {
|
|
260
490
|
while (this.queue.length > 0) {
|
|
261
491
|
const item = this.queue.shift()!;
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
item.
|
|
492
|
+
this.phase = item.kind === "prompt" ? "prompting" : "handoff";
|
|
493
|
+
this.emitStateIfChanged();
|
|
494
|
+
if (item.kind === "prompt") {
|
|
495
|
+
this.emit({ kind: "turn_started", turnId: item.turnId });
|
|
496
|
+
try {
|
|
497
|
+
const result = await this.runPrompt(item);
|
|
498
|
+
this.emit({
|
|
499
|
+
kind: "turn_completed",
|
|
500
|
+
turnId: item.turnId,
|
|
501
|
+
result: copyPromptResult(result),
|
|
502
|
+
});
|
|
503
|
+
item.resolve(result);
|
|
504
|
+
} catch (err) {
|
|
505
|
+
this.emit({ kind: "turn_failed", turnId: item.turnId, error: String(err) });
|
|
506
|
+
item.reject(err);
|
|
507
|
+
}
|
|
508
|
+
} else {
|
|
509
|
+
try {
|
|
510
|
+
item.resolve(await this.runHandoff(item));
|
|
511
|
+
} catch (err) {
|
|
512
|
+
item.reject(err);
|
|
513
|
+
}
|
|
266
514
|
}
|
|
267
515
|
}
|
|
268
516
|
} finally {
|
|
269
517
|
this.pumping = false;
|
|
518
|
+
if (this.phase !== "stopped") this.phase = "idle";
|
|
519
|
+
this.emitStateIfChanged();
|
|
270
520
|
}
|
|
271
521
|
}
|
|
272
522
|
|
|
273
|
-
private async
|
|
274
|
-
this.
|
|
523
|
+
private async runHandoff(item: HandoffQueueItem): Promise<HandoffResult> {
|
|
524
|
+
const fromInternalSessionId = this._internalSessionId;
|
|
525
|
+
let toInternalSessionId: string | undefined;
|
|
526
|
+
let summary: string | undefined;
|
|
527
|
+
this.emit({
|
|
528
|
+
kind: "handoff_started",
|
|
529
|
+
handoffId: item.handoffId,
|
|
530
|
+
fromInternalSessionId,
|
|
531
|
+
});
|
|
532
|
+
await this.appendTranscript({
|
|
533
|
+
v: 1,
|
|
534
|
+
t: "handoff",
|
|
535
|
+
event: "start",
|
|
536
|
+
ts: Date.now(),
|
|
537
|
+
handoffId: item.handoffId,
|
|
538
|
+
fromInternalSessionId,
|
|
539
|
+
...(item.options.summary !== undefined ? { summary: item.options.summary } : {}),
|
|
540
|
+
});
|
|
541
|
+
|
|
542
|
+
try {
|
|
543
|
+
if (this.controller.isDegraded) {
|
|
544
|
+
throw new Error("handoff requires ACP (normal) mode");
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
if (item.options.summary !== undefined) {
|
|
548
|
+
if (!item.options.summary.trim()) throw new Error("handoff summary cannot be blank");
|
|
549
|
+
summary = item.options.summary;
|
|
550
|
+
} else {
|
|
551
|
+
const generated = await this.controller.prompt(HANDOFF_SUMMARY_PROMPT);
|
|
552
|
+
if (generated.status !== "completed" || !generated.text.trim()) {
|
|
553
|
+
throw new Error(`handoff summary generation ${generated.status}`);
|
|
554
|
+
}
|
|
555
|
+
summary = generated.text.trim();
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
const created = await this.controller.newSession();
|
|
559
|
+
if (!created.sessionId) throw new Error("harness returned no session id for handoff");
|
|
560
|
+
toInternalSessionId = created.sessionId;
|
|
561
|
+
this._internalSessionId = toInternalSessionId;
|
|
562
|
+
this.emitStateIfChanged();
|
|
563
|
+
await this.persist();
|
|
564
|
+
|
|
565
|
+
if (toInternalSessionId === fromInternalSessionId) {
|
|
566
|
+
throw new Error("harness did not replace the internal session during handoff");
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
const seeded = await this.controller.prompt(continuationPrompt(summary));
|
|
570
|
+
if (seeded.status !== "completed") {
|
|
571
|
+
throw new Error(`handoff continuation seeding ${seeded.status}`);
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
const result: HandoffResult = Object.freeze({
|
|
575
|
+
handoffId: item.handoffId,
|
|
576
|
+
agentSessionId: this.agentSessionId,
|
|
577
|
+
fromInternalSessionId,
|
|
578
|
+
toInternalSessionId,
|
|
579
|
+
summary,
|
|
580
|
+
});
|
|
581
|
+
await this.appendTranscript({
|
|
582
|
+
v: 1,
|
|
583
|
+
t: "handoff",
|
|
584
|
+
event: "complete",
|
|
585
|
+
ts: Date.now(),
|
|
586
|
+
handoffId: item.handoffId,
|
|
587
|
+
fromInternalSessionId,
|
|
588
|
+
toInternalSessionId,
|
|
589
|
+
summary,
|
|
590
|
+
});
|
|
591
|
+
this.emit({ kind: "handoff_completed", result });
|
|
592
|
+
return result;
|
|
593
|
+
} catch (err) {
|
|
594
|
+
// Once session/new succeeds the controller really is on the new thread. Keep the
|
|
595
|
+
// public id and catalog truthful even when continuation seeding subsequently fails.
|
|
596
|
+
const actualSessionId = this.controller.currentSessionId;
|
|
597
|
+
if (actualSessionId && actualSessionId !== this._internalSessionId) {
|
|
598
|
+
this._internalSessionId = actualSessionId;
|
|
599
|
+
toInternalSessionId = actualSessionId;
|
|
600
|
+
this.emitStateIfChanged();
|
|
601
|
+
try {
|
|
602
|
+
await this.persist();
|
|
603
|
+
} catch (persistError) {
|
|
604
|
+
this.log.warn("handoff_failure_persist_failed", { error: String(persistError) });
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
const error = String(err);
|
|
608
|
+
await this.appendTranscript({
|
|
609
|
+
v: 1,
|
|
610
|
+
t: "handoff",
|
|
611
|
+
event: "failed",
|
|
612
|
+
ts: Date.now(),
|
|
613
|
+
handoffId: item.handoffId,
|
|
614
|
+
fromInternalSessionId,
|
|
615
|
+
...(toInternalSessionId ? { toInternalSessionId } : {}),
|
|
616
|
+
...(summary !== undefined ? { summary } : {}),
|
|
617
|
+
error,
|
|
618
|
+
});
|
|
619
|
+
this.emit({
|
|
620
|
+
kind: "handoff_failed",
|
|
621
|
+
handoffId: item.handoffId,
|
|
622
|
+
fromInternalSessionId,
|
|
623
|
+
...(toInternalSessionId ? { toInternalSessionId } : {}),
|
|
624
|
+
error,
|
|
625
|
+
});
|
|
626
|
+
throw err;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
private async runPrompt(item: PromptQueueItem): Promise<PromptResult> {
|
|
631
|
+
this.beginTurn(item.turnId);
|
|
275
632
|
await this.appendTranscript({
|
|
276
633
|
v: 1,
|
|
277
634
|
t: "msg",
|
|
@@ -354,10 +711,10 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
354
711
|
return this.aggregator.snapshot();
|
|
355
712
|
}
|
|
356
713
|
|
|
357
|
-
private beginTurn(): void {
|
|
714
|
+
private beginTurn(turnId: string): void {
|
|
358
715
|
// A correct caller always gets an empty array back — both exit paths flush. If one
|
|
359
716
|
// ever doesn't, keeping the records (loudly) beats dropping them.
|
|
360
|
-
const leftover = this.aggregator.startTurn(
|
|
717
|
+
const leftover = this.aggregator.startTurn(turnId);
|
|
361
718
|
if (leftover.length > 0) {
|
|
362
719
|
this.log.warn("activity_turn_not_flushed", { records: leftover.length });
|
|
363
720
|
if (this.transcriptActivity) for (const record of leftover) this.writeActivity(record);
|
|
@@ -383,6 +740,10 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
383
740
|
* random suffix covers two turns in the same millisecond.
|
|
384
741
|
*/
|
|
385
742
|
private mintTurnId(): string {
|
|
743
|
+
return this.mintOperationId();
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
private mintOperationId(): string {
|
|
386
747
|
return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
|
387
748
|
}
|
|
388
749
|
|
|
@@ -394,7 +755,7 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
394
755
|
* holds without blocking the agent's update stream on disk.
|
|
395
756
|
*/
|
|
396
757
|
private writeActivity(record: AggregatedRecord): void {
|
|
397
|
-
if (!this.
|
|
758
|
+
if (!this._transcriptPath) return;
|
|
398
759
|
if (!this.activityKinds.has(record.event.kind)) return;
|
|
399
760
|
void this.appendTranscript(this.toActivityLine(record));
|
|
400
761
|
}
|
|
@@ -427,13 +788,25 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
427
788
|
if (options?.clearQueue) {
|
|
428
789
|
const dropped = this.queue.splice(0);
|
|
429
790
|
for (const item of dropped) {
|
|
430
|
-
item.
|
|
791
|
+
if (item.kind === "prompt") {
|
|
792
|
+
item.resolve({ text: "", stopReason: "cancelled", status: "cancelled", usage: null });
|
|
793
|
+
} else {
|
|
794
|
+
item.reject(new Error("handoff cancelled before it started"));
|
|
795
|
+
}
|
|
431
796
|
}
|
|
797
|
+
this.emitStateIfChanged();
|
|
432
798
|
}
|
|
433
799
|
this.controller.interrupt(options);
|
|
434
800
|
}
|
|
435
801
|
|
|
436
802
|
async stop(): Promise<void> {
|
|
803
|
+
if (this.phase === "stopped") return;
|
|
804
|
+
// Stop is terminal for this stable object. Drop work that never started, interrupt the
|
|
805
|
+
// active turn, and publish stopped before awaiting process teardown so a concurrent
|
|
806
|
+
// prompt cannot slip into a controller that is going away.
|
|
807
|
+
this.interrupt({ clearQueue: true });
|
|
808
|
+
this.phase = "stopped";
|
|
809
|
+
this.emitStateIfChanged();
|
|
437
810
|
await this.controller.stop();
|
|
438
811
|
}
|
|
439
812
|
|
|
@@ -462,8 +835,9 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
462
835
|
setConfig(configId: string, value: unknown): Promise<void> {
|
|
463
836
|
return this.controller.setConfig(configId, value);
|
|
464
837
|
}
|
|
465
|
-
|
|
466
|
-
|
|
838
|
+
/** Immutable snapshot of commands advertised by the active ACP harness. */
|
|
839
|
+
get internalSessionCommands(): readonly InternalSessionCommand[] {
|
|
840
|
+
return this.controller.availableCommands;
|
|
467
841
|
}
|
|
468
842
|
get isDegraded(): boolean {
|
|
469
843
|
return this.controller.isDegraded;
|
|
@@ -513,25 +887,69 @@ export class AgentSession implements AgentClient, Bridgeable {
|
|
|
513
887
|
mode: this._mode,
|
|
514
888
|
cwd: this._cwd,
|
|
515
889
|
title: this._title,
|
|
890
|
+
transcriptPath: this._transcriptPath,
|
|
516
891
|
});
|
|
517
892
|
}
|
|
518
893
|
|
|
519
894
|
private async appendTranscript(line: TranscriptLine): Promise<void> {
|
|
520
|
-
if (!this.
|
|
895
|
+
if (!this._transcriptPath) return;
|
|
521
896
|
this.transcriptWrite = this.transcriptWrite
|
|
522
897
|
.catch(() => {})
|
|
523
898
|
.then(async () => {
|
|
524
899
|
try {
|
|
525
|
-
await appendTranscriptLine(this.
|
|
900
|
+
await appendTranscriptLine(this._transcriptPath!, line);
|
|
526
901
|
} catch (err) {
|
|
527
902
|
this.log.warn("transcript_write_failed", {
|
|
528
|
-
path: this.
|
|
903
|
+
path: this._transcriptPath,
|
|
529
904
|
error: String(err),
|
|
530
905
|
});
|
|
531
906
|
}
|
|
532
907
|
});
|
|
533
908
|
await this.transcriptWrite;
|
|
534
909
|
}
|
|
910
|
+
|
|
911
|
+
/** Emit only when a field in the public snapshot changed. */
|
|
912
|
+
private emitStateIfChanged(): void {
|
|
913
|
+
const state = this.state;
|
|
914
|
+
const key = [
|
|
915
|
+
state.phase,
|
|
916
|
+
state.queuedOperationCount,
|
|
917
|
+
state.internalSessionId ?? "",
|
|
918
|
+
state.adapterId,
|
|
919
|
+
state.mode,
|
|
920
|
+
].join("\u0000");
|
|
921
|
+
if (key === this.lastStateKey) return;
|
|
922
|
+
this.lastStateKey = key;
|
|
923
|
+
this.emit({ kind: "state_changed", state });
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
/** Listener failures are observation failures, never session-operation failures. */
|
|
927
|
+
private emit(event: AgentSessionEvent): void {
|
|
928
|
+
const notification: AgentSessionNotification = Object.freeze({
|
|
929
|
+
seq: ++this.notificationSeq,
|
|
930
|
+
ts: Date.now(),
|
|
931
|
+
agentSessionId: this.agentSessionId,
|
|
932
|
+
event: Object.freeze(event),
|
|
933
|
+
});
|
|
934
|
+
for (const listener of [...this.listeners]) {
|
|
935
|
+
try {
|
|
936
|
+
listener(notification);
|
|
937
|
+
} catch (err) {
|
|
938
|
+
this.log.warn("agent_session_listener_failed", {
|
|
939
|
+
kind: event.kind,
|
|
940
|
+
error: String(err),
|
|
941
|
+
});
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
/** Do not let one notification observer mutate the PromptResult another observer sees. */
|
|
948
|
+
function copyPromptResult(result: PromptResult): PromptResult {
|
|
949
|
+
return Object.freeze({
|
|
950
|
+
...result,
|
|
951
|
+
usage: result.usage ? Object.freeze({ ...result.usage }) : null,
|
|
952
|
+
});
|
|
535
953
|
}
|
|
536
954
|
|
|
537
955
|
const encoder = new TextEncoder();
|
package/src/cli/index.ts
CHANGED
|
@@ -21,7 +21,7 @@ import {
|
|
|
21
21
|
createWireLog,
|
|
22
22
|
type AdapterPreset,
|
|
23
23
|
} from "../index.ts";
|
|
24
|
-
import {
|
|
24
|
+
import { createControllerCommands, runRepl } from "../repl/index.ts";
|
|
25
25
|
import { DIM, colorEnabled, paint } from "../repl/colors.ts";
|
|
26
26
|
|
|
27
27
|
interface Args {
|
|
@@ -107,7 +107,7 @@ async function chat(args: Args): Promise<void> {
|
|
|
107
107
|
const color = colorEnabled(process.stderr);
|
|
108
108
|
const note = (s: string) => process.stderr.write(paint(color, DIM, s) + "\n");
|
|
109
109
|
|
|
110
|
-
const commands =
|
|
110
|
+
const commands = createControllerCommands({ client: controller, note, color });
|
|
111
111
|
|
|
112
112
|
try {
|
|
113
113
|
await runRepl(controller, {
|