@qlairoslabs/acp-client 0.11.1 → 0.12.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/CHANGELOG-consumer-fixes.md +62 -0
- package/CHANGELOG-operation-lifecycle.md +64 -0
- package/CONSUMER_GUIDE.md +288 -12
- package/MIGRATION-0.10-to-0.12.md +189 -0
- package/README.md +6 -3
- package/package.json +5 -2
- package/src/adapters.ts +8 -1
- package/src/agent/adoption/replay.ts +1 -0
- package/src/agent/config.ts +4 -0
- package/src/agent/conversation-manager.ts +178 -150
- 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 +535 -94
- package/src/agent.ts +46 -23
- package/src/audit/config.ts +4 -0
- package/src/audit/projection.ts +3 -0
- package/src/checkpointing/recovery.ts +12 -0
- package/src/checkpointing/strategy.ts +2 -0
- package/src/client.ts +132 -30
- package/src/controller.ts +116 -7
- package/src/degraded/pty-client.ts +25 -1
- 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 +86 -10
- 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/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;
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
// `extractReply` is the deterministic default; an injected `parser` (ScreenParser/SML)
|
|
11
11
|
// can replace it for messier TUIs without touching the transport/turn machinery.
|
|
12
12
|
|
|
13
|
+
import type { OutputListener } from "../operations/contracts.ts";
|
|
13
14
|
import type { AgentClient, Bridgeable, BridgeOptions, InterruptOptions } from "../agent-client.ts";
|
|
14
15
|
import type { Adapter } from "../adapters.ts";
|
|
15
16
|
import { prepareLaunch, type AcpLauncher } from "../launcher.ts";
|
|
@@ -20,6 +21,8 @@ import { NotConnectedError } from "../errors.ts";
|
|
|
20
21
|
import { PtyTransport } from "./pty-transport.ts";
|
|
21
22
|
import { EmulatorScreen, compactLines } from "./emulator.ts";
|
|
22
23
|
import { extractReply } from "./extract.ts";
|
|
24
|
+
import { promptParts, partsText } from "../media/parts.ts";
|
|
25
|
+
import type { ClientPrompt } from "../agent-client.ts";
|
|
23
26
|
|
|
24
27
|
const ETX = "\x03"; // Ctrl-C
|
|
25
28
|
const ESC = "\x1b";
|
|
@@ -62,6 +65,7 @@ export class PtyClient implements AgentClient, Bridgeable {
|
|
|
62
65
|
private screen: EmulatorScreen | null = null;
|
|
63
66
|
private turn: Turn | null = null;
|
|
64
67
|
// Raw pty-output subscribers (used by bridge() to mirror the pty to the user's screen).
|
|
68
|
+
private readonly outputListeners = new Set<OutputListener>();
|
|
65
69
|
private rawListeners = new Set<(data: string) => void>();
|
|
66
70
|
private readonly settleMs: number;
|
|
67
71
|
private readonly submitDelayMs: number;
|
|
@@ -77,6 +81,12 @@ export class PtyClient implements AgentClient, Bridgeable {
|
|
|
77
81
|
this.log = opts.logger ?? noopLogger;
|
|
78
82
|
}
|
|
79
83
|
|
|
84
|
+
/** Raw terminal bytes explain activity even before a scraped reply has settled. */
|
|
85
|
+
subscribeOutput(listener: OutputListener): () => void {
|
|
86
|
+
this.outputListeners.add(listener);
|
|
87
|
+
return () => this.outputListeners.delete(listener);
|
|
88
|
+
}
|
|
89
|
+
|
|
80
90
|
get isConnected(): boolean {
|
|
81
91
|
return this.transport !== null;
|
|
82
92
|
}
|
|
@@ -114,10 +124,20 @@ export class PtyClient implements AgentClient, Bridgeable {
|
|
|
114
124
|
}
|
|
115
125
|
|
|
116
126
|
prompt(
|
|
117
|
-
|
|
127
|
+
input: string | ClientPrompt,
|
|
118
128
|
handlers?: PromptHandlers,
|
|
119
129
|
_attachments?: Attachment[],
|
|
120
130
|
): Promise<PromptResult> {
|
|
131
|
+
let text = typeof input === "string" ? input : input.text ?? "";
|
|
132
|
+
if (typeof input !== "string") {
|
|
133
|
+
handlers = input.handlers;
|
|
134
|
+
_attachments = input.attachments;
|
|
135
|
+
}
|
|
136
|
+
const parts = typeof input === "string" ? undefined : promptParts(input);
|
|
137
|
+
if (_attachments?.length || parts?.some((part) => part.kind !== "text" && part.kind !== "pasted")) {
|
|
138
|
+
return Promise.reject(new Error("PTY mode does not support non-text parts"));
|
|
139
|
+
}
|
|
140
|
+
if (parts) text = partsText(parts);
|
|
121
141
|
if (!this.transport || !this.screen) throw new NotConnectedError("PtyClient is not started");
|
|
122
142
|
if (this.turn) throw new Error("PtyClient is busy with another turn");
|
|
123
143
|
|
|
@@ -181,6 +201,10 @@ export class PtyClient implements AgentClient, Bridgeable {
|
|
|
181
201
|
// --- internals ----------------------------------------------------------------
|
|
182
202
|
|
|
183
203
|
private onData(data: string): void {
|
|
204
|
+
for (const listener of [...this.outputListeners]) {
|
|
205
|
+
try { listener({ kind: "update", sessionId: null }); }
|
|
206
|
+
catch (error) { this.log.warn("pty_output_listener_failed", { error: String(error) }); }
|
|
207
|
+
}
|
|
184
208
|
this.screen?.write(data);
|
|
185
209
|
for (const listener of this.rawListeners) listener(data);
|
|
186
210
|
if (this.turn) this.armSettle();
|
package/src/index.ts
CHANGED
|
@@ -98,6 +98,7 @@ export {
|
|
|
98
98
|
CONVERSATION_ERROR_RECOVERABILITIES,
|
|
99
99
|
CONVERSATION_ERROR_SOURCES,
|
|
100
100
|
buildConversationErrorDetails,
|
|
101
|
+
conversationErrorDetailsFromError,
|
|
101
102
|
sanitizeConversationErrorMessage,
|
|
102
103
|
} from "./persistence/error-records.ts";
|
|
103
104
|
export type {
|
|
@@ -129,6 +130,8 @@ export type {
|
|
|
129
130
|
ConversationErrorRecoverability,
|
|
130
131
|
ConversationErrorSource,
|
|
131
132
|
ErrorRecord,
|
|
133
|
+
RecentItemPage,
|
|
134
|
+
RecentItemPageOptions,
|
|
132
135
|
RecentRecordPage,
|
|
133
136
|
RecentRecordPageOptions,
|
|
134
137
|
IdentityMemoryObservation,
|
|
@@ -154,6 +157,8 @@ export type {
|
|
|
154
157
|
ParticipantRef,
|
|
155
158
|
PersistedContent,
|
|
156
159
|
PersistedContentBlock,
|
|
160
|
+
PersistedMediaBlock,
|
|
161
|
+
OutOfBandDeliveryPersistence,
|
|
157
162
|
PersistedIdentitySnapshot,
|
|
158
163
|
PersistedAgentMeteringState,
|
|
159
164
|
PersistedConversationMeteringState,
|
|
@@ -241,6 +246,7 @@ export type {
|
|
|
241
246
|
|
|
242
247
|
export type {
|
|
243
248
|
AgentClient,
|
|
249
|
+
ClientPrompt,
|
|
244
250
|
InterruptOptions,
|
|
245
251
|
Bridgeable,
|
|
246
252
|
BridgeOptions,
|
|
@@ -276,6 +282,7 @@ export type {
|
|
|
276
282
|
PromptDelivery,
|
|
277
283
|
PromptEndedBy,
|
|
278
284
|
PromptHandle,
|
|
285
|
+
CombinedMessage,
|
|
279
286
|
PromptPart,
|
|
280
287
|
} from "./steering/index.ts";
|
|
281
288
|
|
|
@@ -732,3 +739,13 @@ export type {
|
|
|
732
739
|
InternalSessionCommandInput,
|
|
733
740
|
WireEntry,
|
|
734
741
|
} from "./types.ts";
|
|
742
|
+
|
|
743
|
+
export * from "./operations/index.ts";
|
|
744
|
+
|
|
745
|
+
export type { MessagePart, MediaPart, MediaKind, MediaThresholds, ResolvedPart, ResolvedMediaPart } from "./media/parts.ts";
|
|
746
|
+
|
|
747
|
+
export type { MediaStore, MediaInfo, StoredMedia, MediaConfig } from "./media/store.ts";
|
|
748
|
+
|
|
749
|
+
export type { MediaCaptureLevel } from "./media/capture.ts";
|
|
750
|
+
|
|
751
|
+
export type { SharedFile, SharedFilePage, SharedFileQuery, SharedFilesPersistence } from "./media/files.ts";
|
|
@@ -9,6 +9,13 @@ export interface InternalInferenceRetryPolicy {
|
|
|
9
9
|
|
|
10
10
|
export interface InternalInferenceConfig {
|
|
11
11
|
readonly runtime?: InternalInferenceRuntime;
|
|
12
|
+
/**
|
|
13
|
+
* Keep a harness from starting work of its own in a disposable session (OpenCode names the session with a
|
|
14
|
+
* second request that the answer does not wait for, and stopping the process after the answer can cut it
|
|
15
|
+
* off). On by default for the default runtime; `false` leaves the harness as configured. Has no effect
|
|
16
|
+
* with a custom `runtime`. See `withoutHarnessBackgroundWork`.
|
|
17
|
+
*/
|
|
18
|
+
readonly suppressHarnessBackgroundWork?: boolean;
|
|
12
19
|
readonly adapter?: "same" | string;
|
|
13
20
|
readonly maxConcurrency?: number;
|
|
14
21
|
readonly leaseDurationMs?: number;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { OperationActivity } from "../operations/contracts.ts";
|
|
1
2
|
import type { AgentConversationId, AgentSessionId } from "../agent-ids.ts";
|
|
2
3
|
import type { AgentSessionMeteringState } from "../metering/state.ts";
|
|
3
4
|
import type { OperationMeteringRecord, OperationOutcome } from "../metering/record.ts";
|
|
@@ -72,6 +73,7 @@ export interface InternalInferenceCompletion {
|
|
|
72
73
|
}
|
|
73
74
|
|
|
74
75
|
export interface InternalInferenceSnapshot {
|
|
76
|
+
readonly operation?: OperationActivity | null;
|
|
75
77
|
readonly id: InternalInferenceId;
|
|
76
78
|
readonly rootId: InternalInferenceId;
|
|
77
79
|
readonly agentSessionId: AgentSessionId;
|
|
@@ -169,6 +171,7 @@ export interface InternalInferenceRuntime {
|
|
|
169
171
|
}
|
|
170
172
|
|
|
171
173
|
export interface InternalInferenceRuntimeLifecycle {
|
|
174
|
+
operationChanged?(activity: (() => OperationActivity) | null): void;
|
|
172
175
|
stageChanged?(stage: Extract<InternalInferenceStage, "creating_session" | "prompting">): void;
|
|
173
176
|
sessionStarted(input: {
|
|
174
177
|
readonly internalSessionId: string;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { OperationActivity } from "../../operations/contracts.ts";
|
|
1
2
|
import { SubscriptionHub } from "../../observation/subscription-hub.ts";
|
|
2
3
|
import type {
|
|
3
4
|
InternalInference,
|
|
@@ -19,14 +20,22 @@ export class AttemptHandle implements InternalInference {
|
|
|
19
20
|
private readonly deferred = promiseWithResolvers<InternalInferenceCompletion>();
|
|
20
21
|
readonly result = this.deferred.promise;
|
|
21
22
|
|
|
22
|
-
constructor(
|
|
23
|
+
constructor(
|
|
24
|
+
record: InternalInferenceAttemptRecord,
|
|
25
|
+
private readonly cancelRun: (reason?: string) => Promise<void>,
|
|
26
|
+
/** The running attempt's provider operation, for the snapshot. */
|
|
27
|
+
private readonly operation?: () => OperationActivity | null,
|
|
28
|
+
) {
|
|
23
29
|
this.current = snapshotOf(record);
|
|
24
30
|
this.result.catch(() => {});
|
|
25
31
|
this.settle(record);
|
|
26
32
|
}
|
|
27
33
|
|
|
28
34
|
get id(): InternalInferenceId { return this.current.id; }
|
|
29
|
-
get snapshot(): InternalInferenceSnapshot {
|
|
35
|
+
get snapshot(): InternalInferenceSnapshot {
|
|
36
|
+
const operation = this.current.status === "running" ? this.operation?.() ?? null : null;
|
|
37
|
+
return Object.freeze({ ...this.current, operation });
|
|
38
|
+
}
|
|
30
39
|
subscribe(listener: (event: InternalInferenceEvent) => void): () => void { return this.hub.subscribe(listener); }
|
|
31
40
|
cancel(): Promise<void> { return this.cancelRun(); }
|
|
32
41
|
emit(event: InternalInferenceEvent): void { this.hub.emit(event); }
|
|
@@ -1,6 +1,9 @@
|
|
|
1
|
+
import { OperationStalledError } from "../../operations/errors.ts";
|
|
2
|
+
import type { OperationActivity } from "../../operations/contracts.ts";
|
|
1
3
|
import { randomUUID } from "node:crypto";
|
|
2
4
|
import type { AgentSessionId } from "../../agent-ids.ts";
|
|
3
|
-
import type { ConversationRecord, PersistenceBackend } from "../../persistence/backend.ts";
|
|
5
|
+
import type { ConversationRecord, PersistenceBackend, PersistenceJsonValue } from "../../persistence/backend.ts";
|
|
6
|
+
import { conversationErrorDetailsFromError } from "../../persistence/error-records.ts";
|
|
4
7
|
import type { OperationMeteringRecord } from "../../metering/record.ts";
|
|
5
8
|
import { SubscriptionHub } from "../../observation/subscription-hub.ts";
|
|
6
9
|
import { createInternalInferenceId } from "../ids.ts";
|
|
@@ -64,6 +67,7 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
|
|
|
64
67
|
private readonly hub = new SubscriptionHub<InternalInferenceEvent>();
|
|
65
68
|
private readonly registry: InternalInferenceStrategyRegistry;
|
|
66
69
|
private readonly workerId = `iiw-${randomUUID()}`;
|
|
70
|
+
private readonly operationSources = new Map<InternalInferenceId, () => OperationActivity>();
|
|
67
71
|
private readonly attempts = new Map<InternalInferenceId, AttemptHandle>();
|
|
68
72
|
private readonly runs = new Map<InternalInferenceId, RunHandle>();
|
|
69
73
|
private readonly active = new Map<InternalInferenceId, {
|
|
@@ -268,6 +272,11 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
|
|
|
268
272
|
...(prepared.cwd ? { cwd: prepared.cwd } : {}),
|
|
269
273
|
...(prepared.metadata ? { metadata: prepared.metadata } : {}),
|
|
270
274
|
}, abort.signal, {
|
|
275
|
+
operationChanged: (source) => {
|
|
276
|
+
if (source) this.operationSources.set(attempt.internalInferenceId, source);
|
|
277
|
+
else this.operationSources.delete(attempt.internalInferenceId);
|
|
278
|
+
this.publishProgress(attempt.internalInferenceId, "prompting");
|
|
279
|
+
},
|
|
271
280
|
stageChanged: (stage) => this.publishProgress(attempt.internalInferenceId, stage),
|
|
272
281
|
sessionStarted: async (session) => {
|
|
273
282
|
metering = await this.config.beginMetering?.(snapshotOf(attempt), session) ?? null;
|
|
@@ -340,7 +349,8 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
|
|
|
340
349
|
if (this.fenced.has(attempt.internalInferenceId)) return;
|
|
341
350
|
const openedMetering = metering as InternalInferenceMeteringOperation | null;
|
|
342
351
|
if (openedMetering && !meteringRecord) {
|
|
343
|
-
|
|
352
|
+
const cancelled = abort.signal.aborted || error instanceof OperationStalledError;
|
|
353
|
+
meteringRecord = await openedMetering.close({ outcome: cancelled ? "cancelled" : "error", error })
|
|
344
354
|
.catch(() => null);
|
|
345
355
|
}
|
|
346
356
|
if (this.closed && abort.signal.aborted) {
|
|
@@ -349,6 +359,7 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
|
|
|
349
359
|
await this.recordFailure(attempt, leaseToken, error, meteringRecord, writes?.meteringRecords);
|
|
350
360
|
}
|
|
351
361
|
} finally {
|
|
362
|
+
this.operationSources.delete(attempt.internalInferenceId);
|
|
352
363
|
clearInterval(heartbeat);
|
|
353
364
|
(metering as InternalInferenceMeteringOperation | null)?.settled();
|
|
354
365
|
this.active.delete(attempt.internalInferenceId);
|
|
@@ -398,6 +409,7 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
|
|
|
398
409
|
): Promise<void> {
|
|
399
410
|
const strategy = this.registry.get(attempt.purpose, attempt.input.strategyId, attempt.input.version);
|
|
400
411
|
const disposition = strategy?.classifyError(error) ?? { kind: "terminal" as const, code: "unknown_strategy" };
|
|
412
|
+
const failureDetails = conversationErrorDetailsFromError(error);
|
|
401
413
|
const canRetry = disposition.kind === "retryable"
|
|
402
414
|
&& attempt.attemptNumber < this.config.settings.retry.maxAttempts;
|
|
403
415
|
const delay = retryDelay(this.config.settings.retry.backoffMs, attempt.attemptNumber);
|
|
@@ -421,6 +433,7 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
|
|
|
421
433
|
leaseToken,
|
|
422
434
|
error: error instanceof Error ? error.message : String(error),
|
|
423
435
|
failureCode: disposition.code,
|
|
436
|
+
...(failureDetails ? { resultMetadata: failureDetails as PersistenceJsonValue } : {}),
|
|
424
437
|
...(canRetry
|
|
425
438
|
? {
|
|
426
439
|
retry: {
|
|
@@ -439,7 +452,11 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
|
|
|
439
452
|
private ownAttempt(record: InternalInferenceAttemptRecord): AttemptHandle {
|
|
440
453
|
let handle = this.attempts.get(record.internalInferenceId);
|
|
441
454
|
if (!handle) {
|
|
442
|
-
handle = new AttemptHandle(
|
|
455
|
+
handle = new AttemptHandle(
|
|
456
|
+
record,
|
|
457
|
+
(reason) => this.cancel(record.rootInternalInferenceId, reason),
|
|
458
|
+
() => this.operationSources.get(record.internalInferenceId)?.() ?? null,
|
|
459
|
+
);
|
|
443
460
|
this.attempts.set(record.internalInferenceId, handle);
|
|
444
461
|
} else handle.update(record);
|
|
445
462
|
return handle;
|
|
@@ -8,3 +8,5 @@ export { DefaultInternalInferenceManager } from "./coordination/manager.ts";
|
|
|
8
8
|
export type { DefaultInternalInferenceManagerConfig } from "./coordination/manager.ts";
|
|
9
9
|
export type { InternalInferenceRepository } from "./persistence/repository.ts";
|
|
10
10
|
export type * from "./persistence/records.ts";
|
|
11
|
+
export { withoutHarnessBackgroundWork, openCodeConfigWithoutTitle, isOpenCode } from "./runtime/disposable-session-env.ts";
|
|
12
|
+
export type { DisposableSessionLaunch } from "./runtime/disposable-session-env.ts";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AgentConversationId, AgentSessionId } from "../../agent-ids.ts";
|
|
2
|
-
import type { PersistenceJsonValue } from "../../persistence/backend.ts";
|
|
2
|
+
import type { ConversationErrorDetails, PersistenceJsonValue } from "../../persistence/backend.ts";
|
|
3
3
|
import type {
|
|
4
4
|
InternalInferenceChainStatus,
|
|
5
5
|
InternalInferenceCompletion,
|
|
@@ -38,6 +38,8 @@ export interface InternalInferenceAttemptRecord {
|
|
|
38
38
|
readonly completion?: InternalInferenceCompletion;
|
|
39
39
|
readonly error?: string;
|
|
40
40
|
readonly failureCode?: string;
|
|
41
|
+
/** Allow-listed detail of the error behind a failed attempt (RPC code, provider labels), when it had any. */
|
|
42
|
+
readonly failureDetails?: ConversationErrorDetails;
|
|
41
43
|
readonly meteringOperationId?: string;
|
|
42
44
|
readonly metadata?: string;
|
|
43
45
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Database } from "bun:sqlite";
|
|
2
2
|
import type { AgentConversationId, AgentSessionId } from "../../agent-ids.ts";
|
|
3
|
-
import { PersistenceConflictError } from "../../persistence/backend.ts";
|
|
3
|
+
import { PersistenceConflictError, type ConversationErrorDetails } from "../../persistence/backend.ts";
|
|
4
4
|
import type {
|
|
5
5
|
InternalInferenceChainStatus,
|
|
6
6
|
InternalInferenceCompletion,
|
|
@@ -490,6 +490,9 @@ function attemptFromRow(row: AttemptRow): InternalInferenceAttemptRecord {
|
|
|
490
490
|
...(row.result_json && row.status === "completed"
|
|
491
491
|
? { completion: JSON.parse(row.result_json) as InternalInferenceCompletion }
|
|
492
492
|
: {}),
|
|
493
|
+
...(row.result_json && row.status === "failed"
|
|
494
|
+
? { failureDetails: JSON.parse(row.result_json) as ConversationErrorDetails }
|
|
495
|
+
: {}),
|
|
493
496
|
...(row.error ? { error: row.error } : {}),
|
|
494
497
|
...(row.failure_code ? { failureCode: row.failure_code } : {}),
|
|
495
498
|
...(row.metering_operation_id ? { meteringOperationId: row.metering_operation_id } : {}),
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { basename } from "node:path";
|
|
2
|
+
import type { Adapter } from "../../adapters.ts";
|
|
3
|
+
import type { AcpLauncher } from "../../launcher.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A disposable session is one prompt and one answer, then its process is stopped. A harness may start work
|
|
7
|
+
* of its own in that session that the prompt's answer does not wait for: OpenCode names a session by
|
|
8
|
+
* running a second request on a small model at the first prompt, in parallel with the answer, and ACP
|
|
9
|
+
* never says when it ends. Stopping the process right after the answer can cancel it mid-stream, so a
|
|
10
|
+
* request nobody reads is left cut off (and, behind a gateway, half-accounted).
|
|
11
|
+
*
|
|
12
|
+
* Nothing in ACP lets the client wait for such work, so the only safe thing is to not start it. This
|
|
13
|
+
* returns the environment variable that does that for a harness known to need it, for internal inference
|
|
14
|
+
* only; conversations are not touched.
|
|
15
|
+
*/
|
|
16
|
+
const OPENCODE_CONFIG = "OPENCODE_CONFIG_CONTENT";
|
|
17
|
+
|
|
18
|
+
export function isOpenCode(adapterId: string, adapter: Pick<Adapter, "command">): boolean {
|
|
19
|
+
return adapterId === "opencode" || adapter.command.some((part) => basename(part) === "opencode");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* `existing` with the title agent disabled. OpenCode reads inline config as JSON; whatever else the consumer
|
|
24
|
+
* put there is kept. Unparseable config is left alone: the harness will refuse it either way, and replacing
|
|
25
|
+
* it would hide the consumer's mistake.
|
|
26
|
+
*/
|
|
27
|
+
export function openCodeConfigWithoutTitle(existing: string | undefined): string | undefined {
|
|
28
|
+
let config: Record<string, unknown> = {};
|
|
29
|
+
if (existing !== undefined && existing.trim() !== "") {
|
|
30
|
+
try {
|
|
31
|
+
const parsed: unknown = JSON.parse(existing);
|
|
32
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return undefined;
|
|
33
|
+
config = parsed as Record<string, unknown>;
|
|
34
|
+
} catch {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
const agent = isObject(config.agent) ? config.agent : {};
|
|
39
|
+
const title = isObject(agent.title) ? agent.title : {};
|
|
40
|
+
return JSON.stringify({ ...config, agent: { ...agent, title: { ...title, disable: true } } });
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface DisposableSessionLaunch {
|
|
44
|
+
readonly env?: Record<string, string>;
|
|
45
|
+
readonly launcher?: AcpLauncher;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The launch settings for a disposable session of `adapterId`: the consumer's `env` and `launcher` with the
|
|
50
|
+
* harness's background work switched off where the harness is known to start some.
|
|
51
|
+
*
|
|
52
|
+
* Without a launcher the variable goes into `env`, which is laid over this process's environment. With
|
|
53
|
+
* one, the launcher's `spawnEnv` is the whole environment of the process it spawns, so the variable is
|
|
54
|
+
* added there; a launcher that starts the harness somewhere else (a container, a remote host) has to
|
|
55
|
+
* forward `OPENCODE_CONFIG_CONTENT` itself, as it does for any other variable.
|
|
56
|
+
*/
|
|
57
|
+
export function withoutHarnessBackgroundWork(
|
|
58
|
+
adapterId: string,
|
|
59
|
+
adapter: Pick<Adapter, "command">,
|
|
60
|
+
launch: DisposableSessionLaunch,
|
|
61
|
+
): DisposableSessionLaunch {
|
|
62
|
+
if (!isOpenCode(adapterId, adapter)) return launch;
|
|
63
|
+
const { launcher } = launch;
|
|
64
|
+
if (launcher) {
|
|
65
|
+
return {
|
|
66
|
+
...launch,
|
|
67
|
+
launcher: {
|
|
68
|
+
async prepare(request) {
|
|
69
|
+
const prepared = await launcher.prepare(request);
|
|
70
|
+
const value = openCodeConfigWithoutTitle(prepared.spawnEnv?.[OPENCODE_CONFIG]);
|
|
71
|
+
return value === undefined
|
|
72
|
+
? prepared
|
|
73
|
+
: { ...prepared, spawnEnv: { ...prepared.spawnEnv, [OPENCODE_CONFIG]: value } };
|
|
74
|
+
},
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
const value = openCodeConfigWithoutTitle(launch.env?.[OPENCODE_CONFIG] ?? process.env[OPENCODE_CONFIG]);
|
|
79
|
+
return value === undefined ? launch : { ...launch, env: { ...launch.env, [OPENCODE_CONFIG]: value } };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function isObject(value: unknown): value is Record<string, unknown> {
|
|
83
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
84
|
+
}
|