@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
|
@@ -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();
|
|
@@ -160,7 +160,7 @@ export class CheckpointBackedIdentityRuntime implements AgentIdentityRuntime {
|
|
|
160
160
|
const header = `Source conversation ${conversation.agentConversationId}${label}; participants=${JSON.stringify(participants)}\n`;
|
|
161
161
|
if (header.length >= maxChars) return null;
|
|
162
162
|
const start = cursor?.deliveredThroughSequence ?? 0;
|
|
163
|
-
const initialSummary = !cursor && checkpoint
|
|
163
|
+
const initialSummary = !cursor && checkpoint?.summary
|
|
164
164
|
? summaryText(checkpoint, "Summary")
|
|
165
165
|
: "";
|
|
166
166
|
const summaryFits = initialSummary.length > 0 && header.length + initialSummary.length <= maxChars;
|
|
@@ -173,7 +173,7 @@ export class CheckpointBackedIdentityRuntime implements AgentIdentityRuntime {
|
|
|
173
173
|
);
|
|
174
174
|
let text = header + (summaryFits ? initialSummary : "") + raw.text;
|
|
175
175
|
let throughSequence = Math.max(from, raw.throughSequence);
|
|
176
|
-
if (cursor && !raw.complete && checkpoint && checkpoint.coveredSequence > throughSequence) {
|
|
176
|
+
if (cursor && !raw.complete && checkpoint?.summary && checkpoint.coveredSequence > throughSequence) {
|
|
177
177
|
const replacement = summaryText(checkpoint, "Updated summary, superseding earlier source context");
|
|
178
178
|
if (header.length + replacement.length <= maxChars) {
|
|
179
179
|
const tail = await this.readMessages(
|
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
|
+
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { OperationSupervisor } from "../../operations/supervisor.ts";
|
|
2
|
+
import type { OutputListener } from "../../operations/contracts.ts";
|
|
1
3
|
import { AgentController, type AgentControllerConfig } from "../../controller.ts";
|
|
2
4
|
import type { PromptResult } from "../../types.ts";
|
|
3
5
|
import type {
|
|
@@ -16,6 +18,9 @@ export interface HarnessInternalInferenceRuntimeConfig {
|
|
|
16
18
|
export interface InternalInferenceController {
|
|
17
19
|
startFresh(): Promise<{ sessionId: string }>;
|
|
18
20
|
prompt(text: string): Promise<PromptResult>;
|
|
21
|
+
subscribeOutput?(listener: OutputListener): () => void;
|
|
22
|
+
cancel?(): void;
|
|
23
|
+
forceStop?(): Promise<void>;
|
|
19
24
|
interrupt(): void;
|
|
20
25
|
stop(): Promise<void>;
|
|
21
26
|
}
|
|
@@ -41,7 +46,8 @@ export class HarnessInternalInferenceRuntime implements InternalInferenceRuntime
|
|
|
41
46
|
};
|
|
42
47
|
const controller = this.config.createController?.(controllerConfig)
|
|
43
48
|
?? new AgentController(controllerConfig);
|
|
44
|
-
|
|
49
|
+
let supervisor: OperationSupervisor | undefined;
|
|
50
|
+
const abort = () => supervisor ? supervisor.cancel("abort") : controller.interrupt();
|
|
45
51
|
signal?.addEventListener("abort", abort, { once: true });
|
|
46
52
|
try {
|
|
47
53
|
if (signal?.aborted) throw abortError();
|
|
@@ -50,7 +56,17 @@ export class HarnessInternalInferenceRuntime implements InternalInferenceRuntime
|
|
|
50
56
|
await lifecycle?.sessionStarted({ internalSessionId: connection.sessionId, model: null });
|
|
51
57
|
if (signal?.aborted) throw abortError();
|
|
52
58
|
lifecycle?.stageChanged?.("prompting");
|
|
53
|
-
|
|
59
|
+
supervisor = new OperationSupervisor({
|
|
60
|
+
prompt: () => controller.prompt(request.prompt),
|
|
61
|
+
subscribeOutput: (listener) => controller.subscribeOutput?.(listener) ?? (() => {}),
|
|
62
|
+
cancel: () => controller.cancel ? controller.cancel() : controller.interrupt(),
|
|
63
|
+
forceStop: () => controller.forceStop ? controller.forceStop() : controller.stop(),
|
|
64
|
+
}, { operationId: request.internalInferenceId, kind: "internal_inference", sessionId: connection.sessionId,
|
|
65
|
+
cancelGraceMs: controllerConfig.adapter.cancelGraceMs,
|
|
66
|
+
limits: controllerConfig.operationLifecycle?.internalInference,
|
|
67
|
+
onStageChanged: () => lifecycle?.operationChanged?.(() => supervisor!.activity),
|
|
68
|
+
});
|
|
69
|
+
const result = await supervisor.run();
|
|
54
70
|
if (result.status !== "completed") {
|
|
55
71
|
throw new Error(`internal inference prompt ${result.status}: ${result.stopReason}`);
|
|
56
72
|
}
|
|
@@ -65,6 +81,7 @@ export class HarnessInternalInferenceRuntime implements InternalInferenceRuntime
|
|
|
65
81
|
...(request.metadata ? { metadata: request.metadata } : {}),
|
|
66
82
|
});
|
|
67
83
|
} finally {
|
|
84
|
+
lifecycle?.operationChanged?.(null);
|
|
68
85
|
signal?.removeEventListener("abort", abort);
|
|
69
86
|
await controller.stop();
|
|
70
87
|
}
|
package/src/media/acp.ts
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type { ContentBlock } from "@agentclientprotocol/sdk";
|
|
3
|
+
import type { Attachment } from "../types.ts";
|
|
4
|
+
import { isMediaPart, mediaKind, type MessagePart, type ResolvedPart } from "./parts.ts";
|
|
5
|
+
|
|
6
|
+
/** What an agent's `promptCapabilities` allow beyond text and links (always allowed by ACP). */
|
|
7
|
+
export interface MediaCapabilities {
|
|
8
|
+
image?: boolean;
|
|
9
|
+
audio?: boolean;
|
|
10
|
+
embeddedContext?: boolean;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** The uri of an embedded copy, which names the copy, not a file. */
|
|
14
|
+
export const EMBEDDED_URI_SCHEME = "attachment:///";
|
|
15
|
+
|
|
16
|
+
/** MIME types sent as an embedded text resource rather than a base64 blob. */
|
|
17
|
+
const TEXT_MIME_TYPES = new Set(["image/svg+xml", "application/json"]);
|
|
18
|
+
|
|
19
|
+
/** Compatibility attachments are copies whose bytes are not kept. */
|
|
20
|
+
export function attachmentParts(attachments: readonly Attachment[] = []): MessagePart[] {
|
|
21
|
+
return attachments.map((attachment) => ({
|
|
22
|
+
kind: mediaKind(attachment.mimeType),
|
|
23
|
+
mimeType: attachment.mimeType,
|
|
24
|
+
data: new Uint8Array(attachment.data),
|
|
25
|
+
mode: "copy",
|
|
26
|
+
keep: false,
|
|
27
|
+
}));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Whether the agent accepts a copy of this kind. */
|
|
31
|
+
export function supportsCopy(kind: ResolvedPart["kind"], capabilities?: MediaCapabilities): boolean {
|
|
32
|
+
if (kind === "text" || kind === "pasted") return true;
|
|
33
|
+
return Boolean(capabilities?.[kind === "file" ? "embeddedContext" : kind]);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function partsToAcp(parts: readonly ResolvedPart[]): ContentBlock[] {
|
|
37
|
+
return parts.map((part): ContentBlock => {
|
|
38
|
+
if (!isMediaPart(part)) return { type: "text", text: part.text };
|
|
39
|
+
if (part.mode === "link") {
|
|
40
|
+
return {
|
|
41
|
+
type: "resource_link",
|
|
42
|
+
uri: part.uri!,
|
|
43
|
+
name: part.name ?? "file",
|
|
44
|
+
mimeType: part.mimeType,
|
|
45
|
+
...(part.size !== undefined ? { size: part.size } : {}),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
const data = Buffer.from(part.data!).toString("base64");
|
|
49
|
+
if (part.kind === "image" || part.kind === "audio") return { type: part.kind, data, mimeType: part.mimeType };
|
|
50
|
+
// The content travels in the block: a `file://` uri would name a path that does not exist.
|
|
51
|
+
const uri = `${EMBEDDED_URI_SCHEME}${encodeURIComponent(part.name ?? "attachment")}`;
|
|
52
|
+
if (part.mimeType.startsWith("text/") || TEXT_MIME_TYPES.has(part.mimeType)) {
|
|
53
|
+
const text = new TextDecoder().decode(part.data);
|
|
54
|
+
return { type: "resource", resource: { uri, mimeType: part.mimeType, text } };
|
|
55
|
+
}
|
|
56
|
+
return { type: "resource", resource: { uri, mimeType: part.mimeType, blob: data } };
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Normalize an agent content chunk without fetching resource links. */
|
|
61
|
+
export function acpToPart(block: ContentBlock): ResolvedPart | undefined {
|
|
62
|
+
switch (block.type) {
|
|
63
|
+
case "text":
|
|
64
|
+
return { kind: "text", text: block.text };
|
|
65
|
+
case "resource_link":
|
|
66
|
+
return {
|
|
67
|
+
kind: mediaKind(block.mimeType ?? undefined),
|
|
68
|
+
mode: "link",
|
|
69
|
+
uri: block.uri,
|
|
70
|
+
name: block.name,
|
|
71
|
+
mimeType: block.mimeType ?? "application/octet-stream",
|
|
72
|
+
...(block.size != null ? { size: block.size } : {}),
|
|
73
|
+
};
|
|
74
|
+
case "image":
|
|
75
|
+
case "audio": {
|
|
76
|
+
const data = new Uint8Array(Buffer.from(block.data, "base64"));
|
|
77
|
+
return {
|
|
78
|
+
kind: block.type === "image" && block.mimeType === "image/svg+xml" ? "file" : block.type,
|
|
79
|
+
mode: "copy",
|
|
80
|
+
data,
|
|
81
|
+
mimeType: block.mimeType,
|
|
82
|
+
size: data.byteLength,
|
|
83
|
+
sha256: hashBytes(data),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
case "resource": {
|
|
87
|
+
const resource = block.resource;
|
|
88
|
+
const isText = "text" in resource;
|
|
89
|
+
const data = isText
|
|
90
|
+
? new TextEncoder().encode(resource.text)
|
|
91
|
+
: new Uint8Array(Buffer.from(resource.blob, "base64"));
|
|
92
|
+
const name = resource.uri.split("/").at(-1) || undefined;
|
|
93
|
+
return {
|
|
94
|
+
kind: "file",
|
|
95
|
+
mode: "copy",
|
|
96
|
+
data,
|
|
97
|
+
mimeType: resource.mimeType ?? (isText ? "text/plain" : "application/octet-stream"),
|
|
98
|
+
...(name ? { name } : {}),
|
|
99
|
+
size: data.byteLength,
|
|
100
|
+
sha256: hashBytes(data),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
default:
|
|
104
|
+
return undefined;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function hashBytes(data: Uint8Array): string {
|
|
109
|
+
return createHash("sha256").update(data).digest("hex");
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** An explicit copy the agent cannot take is refused: nothing is silently dropped. */
|
|
113
|
+
export function assertPartCapabilities(parts: readonly ResolvedPart[], capabilities?: MediaCapabilities): void {
|
|
114
|
+
for (const part of parts) {
|
|
115
|
+
if (!isMediaPart(part) || part.mode === "link") continue;
|
|
116
|
+
if (!supportsCopy(part.kind, capabilities)) throw new Error(`agent does not support ${part.kind} copies`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { PersistedContent, PersistedContentBlock } from "../persistence/backend.ts";
|
|
2
|
+
|
|
3
|
+
export type MediaCaptureLevel = "none" | "metadata" | "content";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Apply the message capture level to a record's content. Media blocks are left as they are: the
|
|
7
|
+
* `media` capture level, and each part's own `keep` and `record`, were applied when the parts were
|
|
8
|
+
* persisted (`persistParts`, the only place media blocks are built), so the record already holds
|
|
9
|
+
* what was decided for them.
|
|
10
|
+
*/
|
|
11
|
+
export function captureMessageContent(content: PersistedContent, text: boolean): PersistedContent {
|
|
12
|
+
if (typeof content === "string") return text ? content : "";
|
|
13
|
+
const blocks: PersistedContentBlock[] = content.filter((block) => block.type === "media" || text);
|
|
14
|
+
return blocks.length === 0 ? "" : blocks;
|
|
15
|
+
}
|