@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
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { writeConversationError } from "./error-record-writer.ts";
|
|
2
|
+
import type { OperationStalledError } from "../operations/errors.ts";
|
|
1
3
|
import { randomUUID } from "node:crypto";
|
|
2
4
|
import {
|
|
3
5
|
type AgentConversationId,
|
|
@@ -21,7 +23,7 @@ import type {
|
|
|
21
23
|
} from "../agent-conversation-owner.ts";
|
|
22
24
|
import { OwnedPromptPostCommitError } from "../agent-conversation-owner.ts";
|
|
23
25
|
import {
|
|
24
|
-
|
|
26
|
+
composeProviderParts,
|
|
25
27
|
pendingOutOfBandMessages,
|
|
26
28
|
} from "../out-of-band-messages.ts";
|
|
27
29
|
import type {
|
|
@@ -38,23 +40,56 @@ import {
|
|
|
38
40
|
} from "./record-capture.ts";
|
|
39
41
|
|
|
40
42
|
import type { Agent } from "../agent.ts";
|
|
43
|
+
import { deliverableParts, pendingOutOfBandParts } from "../media/pending.ts";
|
|
44
|
+
import { resolveParts } from "../media/store.ts";
|
|
45
|
+
import { attachmentParts } from "../media/acp.ts";
|
|
46
|
+
import { contentParts, persistParts } from "../media/content.ts";
|
|
47
|
+
import { isMediaPart, type ResolvedPart } from "../media/parts.ts";
|
|
48
|
+
import type { MediaStore } from "../media/store.ts";
|
|
41
49
|
|
|
42
50
|
export class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle {
|
|
51
|
+
private readonly outputMedia = new WeakMap<object, string>();
|
|
52
|
+
private readonly deliveredMessages = new Map<string, { ids: readonly string[]; throughSequence: number }>();
|
|
43
53
|
constructor(
|
|
44
54
|
private readonly agent: Agent,
|
|
45
55
|
private readonly conversationId: AgentConversationId,
|
|
46
56
|
private readonly initialParticipants: readonly ParticipantRef[],
|
|
47
57
|
private readonly settings: ManagerSettings,
|
|
58
|
+
readonly recoverInPlace?: (error: unknown) => Promise<void>,
|
|
48
59
|
) {}
|
|
49
60
|
|
|
61
|
+
async operationFailed(input: { operationId: string; error: OperationStalledError }): Promise<void> {
|
|
62
|
+
const written = await writeConversationError(this.agent, this.settings, {
|
|
63
|
+
agentConversationId: this.conversationId, attemptId: input.operationId,
|
|
64
|
+
operationId: input.operationId, source: "operation", code: "stalled", recoverability: "retryable",
|
|
65
|
+
message: "The provider stopped producing output.", details: { phase: input.error.phase },
|
|
66
|
+
});
|
|
67
|
+
if (written.recordingError) throw written.recordingError;
|
|
68
|
+
}
|
|
69
|
+
|
|
50
70
|
async beforePrompt(input: OwnedPromptInput) {
|
|
51
71
|
// A combined prompt records each original message as it was sent, under the same operation.
|
|
52
72
|
const parts = input.parts ?? [{
|
|
53
73
|
id: input.operationId,
|
|
54
74
|
text: input.text,
|
|
75
|
+
messageParts: input.messageParts,
|
|
76
|
+
attachments: input.attachments,
|
|
55
77
|
...(input.participantId ? { participantId: input.participantId } : {}),
|
|
56
78
|
...(input.consumerMetadata !== undefined ? { consumerMetadata: input.consumerMetadata } : {}),
|
|
57
79
|
}];
|
|
80
|
+
const resolved = await Promise.all(parts.map((message) => resolveParts([
|
|
81
|
+
...(message.messageParts ?? [{ kind: "text" as const, text: message.text }]),
|
|
82
|
+
...attachmentParts(message.attachments),
|
|
83
|
+
], {
|
|
84
|
+
cwd: input.mediaContext?.cwd ?? process.cwd(),
|
|
85
|
+
capabilities: input.mediaContext?.capabilities,
|
|
86
|
+
thresholds: this.agent.media.thresholds,
|
|
87
|
+
owner: this.conversationId,
|
|
88
|
+
store: this.mediaStore(),
|
|
89
|
+
})));
|
|
90
|
+
if (input.mediaContext?.degraded && resolved.some((message) => message.some(isMediaPart))) {
|
|
91
|
+
throw new Error("PTY mode does not support non-text parts");
|
|
92
|
+
}
|
|
58
93
|
const participants: ParticipantRef[] = [];
|
|
59
94
|
for (const part of parts) participants.push(await this.resolveParticipant(part.participantId));
|
|
60
95
|
const participant = participants[0]!;
|
|
@@ -69,31 +104,51 @@ export class PersistedConversationLifecycle implements AgentConversationOwnerLif
|
|
|
69
104
|
? { timeoutMs: this.settings.identityTimeoutMs }
|
|
70
105
|
: {}),
|
|
71
106
|
});
|
|
72
|
-
const records
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
107
|
+
const records: ConversationRecord[] = [];
|
|
108
|
+
await this.agent.persistence.transaction(async (scope) => {
|
|
109
|
+
const contents = await Promise.all(resolved.map((message) =>
|
|
110
|
+
persistParts(message, this.conversationId, this.mediaStore(scope), this.settings.capture.media)));
|
|
111
|
+
const userRecords = parts.map((part, index): NewConversationRecord => ({
|
|
112
|
+
recordId: index === 0 ? `${input.operationId}:user` : `${input.operationId}:user:${index + 1}`,
|
|
113
|
+
agentSessionId: this.agent.id,
|
|
114
|
+
agentConversationId: this.conversationId,
|
|
115
|
+
kind: "message",
|
|
116
|
+
timestamp: new Date().toISOString(),
|
|
117
|
+
operationId: input.operationId,
|
|
118
|
+
role: "user",
|
|
119
|
+
participantId: participants[index]!.id,
|
|
120
|
+
...(part.consumerMetadata !== undefined ? { consumerMetadata: part.consumerMetadata } : {}),
|
|
121
|
+
content: contents[index]!,
|
|
122
|
+
status: "completed",
|
|
123
|
+
metadata: JSON.stringify({ operationId: input.operationId }),
|
|
124
|
+
}));
|
|
125
|
+
await this.persistObservationsInTransaction(scope, userRecords, true, records);
|
|
126
|
+
});
|
|
127
|
+
this.agent.publishCommittedRecords(records);
|
|
128
|
+
if (this.settings.auditLog) this.agent.audit?.notifyPending();
|
|
85
129
|
await this.updateIdentity(records);
|
|
86
130
|
// Read after the user record commits so a concurrent append falls in this turn or the next.
|
|
87
|
-
const
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
131
|
+
const currentUserSequence = records[0]?.sequence
|
|
132
|
+
?? ((await this.agent.persistence.conversations.get(this.conversationId))!.latestSequence + 1);
|
|
133
|
+
const outOfBand = await pendingOutOfBandMessages(this.agent.persistence, this.conversationId,
|
|
134
|
+
input.targetProviderContextId, currentUserSequence);
|
|
135
|
+
const ordered: ResolvedPart[] = resolved.flatMap((parts, index) => [
|
|
136
|
+
...(index ? [{ kind: "text" as const, text: "\n\n" }] : []), ...parts,
|
|
137
|
+
]);
|
|
138
|
+
this.deliveredMessages.set(input.operationId, {
|
|
139
|
+
ids: outOfBand.map((message) => message.recordId),
|
|
140
|
+
throughSequence: currentUserSequence - 1,
|
|
141
|
+
});
|
|
142
|
+
const store = this.mediaStore();
|
|
143
|
+
const pending = pendingOutOfBandParts(this.agent);
|
|
144
|
+
const providerParts = await composeProviderParts(ordered, identity.promptPreamble, outOfBand, async (message) =>
|
|
145
|
+
deliverableParts(
|
|
146
|
+
pending.get(message.recordId)?.parts ?? await contentParts(message.content, store),
|
|
147
|
+
input.mediaContext?.capabilities,
|
|
148
|
+
input.mediaContext?.degraded,
|
|
149
|
+
));
|
|
95
150
|
return Object.freeze({
|
|
96
|
-
|
|
151
|
+
providerParts,
|
|
97
152
|
participant,
|
|
98
153
|
participants: Object.freeze(participants),
|
|
99
154
|
...(identity.deliveryReceipt ? { identityDeliveryReceipt: identity.deliveryReceipt } : {}),
|
|
@@ -103,25 +158,38 @@ export class PersistedConversationLifecycle implements AgentConversationOwnerLif
|
|
|
103
158
|
async afterPrompt(input: OwnedPromptCompleted): Promise<OwnedPromptCommitResult> {
|
|
104
159
|
const timestamp = new Date().toISOString();
|
|
105
160
|
const status = input.result.status === "error" ? "failed" : input.result.status;
|
|
161
|
+
const ends = input.messageEnds ?? [];
|
|
106
162
|
const records = input.result.messages.map((message, index): NewConversationRecord => ({
|
|
107
163
|
recordId: `${input.operationId}:assistant:${index + 1}`,
|
|
108
164
|
agentSessionId: this.agent.id,
|
|
109
165
|
agentConversationId: this.conversationId,
|
|
110
166
|
kind: "message",
|
|
111
|
-
timestamp,
|
|
167
|
+
timestamp: ends[index] ?? timestamp,
|
|
168
|
+
operationId: input.operationId,
|
|
112
169
|
role: "assistant",
|
|
113
170
|
logicalMessageId: `message:${input.operationId}:assistant:${index + 1}`,
|
|
114
171
|
content: message.text,
|
|
115
|
-
status,
|
|
172
|
+
status: ends[index] ? "completed" : status,
|
|
116
173
|
metadata: JSON.stringify({
|
|
117
174
|
operationId: input.operationId,
|
|
118
175
|
...(message.messageId ? { providerMessageId: message.messageId } : {}),
|
|
119
176
|
}),
|
|
120
177
|
}));
|
|
121
178
|
const persisted: ConversationRecord[] = [];
|
|
179
|
+
const pending: Array<readonly [object, string]> = [];
|
|
122
180
|
let providerAttachment: ProviderAttachmentCommitAcknowledgement | undefined;
|
|
123
181
|
await this.agent.persistence.transaction(async (persistence) => {
|
|
124
|
-
await this.
|
|
182
|
+
const prepared = await this.withStoredParts(
|
|
183
|
+
persistence, records, input.result.messages.map((message) => message.parts), pending);
|
|
184
|
+
await this.persistObservationsInTransaction(persistence, prepared, true, persisted);
|
|
185
|
+
// Delivery is tracked per provider context, so it holds when no user or assistant text is captured.
|
|
186
|
+
const delivered = this.deliveredMessages.get(input.operationId);
|
|
187
|
+
if (status === "completed" && delivered) {
|
|
188
|
+
const providerContext = input.providerAttachment.kind === "absent"
|
|
189
|
+
? input.targetProviderContextId ?? ""
|
|
190
|
+
: input.providerAttachment.descriptor.internalSessionId;
|
|
191
|
+
await persistence.outOfBandDelivery?.advance(this.conversationId, providerContext, delivered.throughSequence);
|
|
192
|
+
}
|
|
125
193
|
if (status === "completed" && input.providerAttachment.kind === "runtime_only") {
|
|
126
194
|
const descriptor = input.providerAttachment.descriptor;
|
|
127
195
|
const providerSessionRecordId = `provider-${randomUUID()}`;
|
|
@@ -145,6 +213,10 @@ export class PersistedConversationLifecycle implements AgentConversationOwnerLif
|
|
|
145
213
|
});
|
|
146
214
|
}
|
|
147
215
|
});
|
|
216
|
+
const deliveredIds = this.deliveredMessages.get(input.operationId)?.ids ?? [];
|
|
217
|
+
if (status === "completed") for (const id of deliveredIds) pendingOutOfBandParts(this.agent).delete(id);
|
|
218
|
+
this.deliveredMessages.delete(input.operationId);
|
|
219
|
+
for (const [part, ref] of pending) this.outputMedia.set(part, ref);
|
|
148
220
|
this.agent.publishCommittedRecords(persisted);
|
|
149
221
|
if (this.settings.auditLog) this.agent.audit?.notifyPending();
|
|
150
222
|
const commit: OwnedPromptCommitResult = Object.freeze({
|
|
@@ -165,23 +237,28 @@ export class PersistedConversationLifecycle implements AgentConversationOwnerLif
|
|
|
165
237
|
}
|
|
166
238
|
|
|
167
239
|
async promptFailed(input: OwnedPromptFailed): Promise<void> {
|
|
240
|
+
this.deliveredMessages.delete(input.operationId);
|
|
168
241
|
const timestamp = new Date().toISOString();
|
|
242
|
+
const ends = input.messageEnds ?? [];
|
|
169
243
|
const records = input.messages.map((message, index): NewConversationRecord => ({
|
|
170
244
|
recordId: `${input.operationId}:assistant:${index + 1}`,
|
|
171
245
|
agentSessionId: this.agent.id,
|
|
172
246
|
agentConversationId: this.conversationId,
|
|
173
247
|
kind: "message",
|
|
174
|
-
timestamp,
|
|
248
|
+
timestamp: ends[index] ?? timestamp,
|
|
249
|
+
operationId: input.operationId,
|
|
175
250
|
role: "assistant",
|
|
176
251
|
logicalMessageId: `message:${input.operationId}:assistant:${index + 1}`,
|
|
177
252
|
content: message.text,
|
|
178
|
-
|
|
253
|
+
// A message that ended before the failure was complete; only the one cut off failed.
|
|
254
|
+
status: ends[index] ? "completed" : "failed",
|
|
179
255
|
metadata: JSON.stringify({
|
|
180
256
|
operationId: input.operationId,
|
|
181
257
|
...(message.messageId ? { providerMessageId: message.messageId } : {}),
|
|
182
258
|
}),
|
|
183
259
|
}));
|
|
184
|
-
|
|
260
|
+
const parts = input.messages.map((message) => message.parts);
|
|
261
|
+
await this.updateIdentity(await this.persistMessagesWithParts(records, parts));
|
|
185
262
|
}
|
|
186
263
|
|
|
187
264
|
resolveAdapter(adapterId: string) {
|
|
@@ -216,13 +293,53 @@ export class PersistedConversationLifecycle implements AgentConversationOwnerLif
|
|
|
216
293
|
return await this.resolveParticipant();
|
|
217
294
|
}
|
|
218
295
|
|
|
219
|
-
async record(record: NewConversationRecord): Promise<void> {
|
|
296
|
+
async record(record: NewConversationRecord, parts?: readonly ResolvedPart[]): Promise<void> {
|
|
220
297
|
const streamingSnapshot = record.kind === "message" && record.status === "in_progress";
|
|
221
|
-
const persisted =
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
298
|
+
const persisted = parts
|
|
299
|
+
? await this.persistMessagesWithParts([record], [parts], !streamingSnapshot)
|
|
300
|
+
: await this.persistObservations([record], !streamingSnapshot);
|
|
301
|
+
if (!streamingSnapshot) await this.updateIdentity(persisted);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** The consumer's store when the Agent has one, otherwise the persistence backend's. */
|
|
305
|
+
private mediaStore(scope: PersistenceScope = this.agent.persistence): MediaStore | undefined {
|
|
306
|
+
return this.agent.media.store ?? scope.media;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Message records whose content is their parts, with the kept copies stored. A copy stored by an
|
|
311
|
+
* earlier revision of the same message keeps its ref, so a streamed message stores it once.
|
|
312
|
+
*/
|
|
313
|
+
private async withStoredParts(
|
|
314
|
+
scope: PersistenceScope,
|
|
315
|
+
records: readonly NewConversationRecord[],
|
|
316
|
+
parts: readonly (readonly ResolvedPart[] | undefined)[],
|
|
317
|
+
pending: Array<readonly [object, string]>,
|
|
318
|
+
): Promise<NewConversationRecord[]> {
|
|
319
|
+
return await Promise.all(records.map(async (record, index) => {
|
|
320
|
+
const messageParts = parts[index];
|
|
321
|
+
if (!messageParts || record.kind !== "message") return record;
|
|
322
|
+
const content = await persistParts(messageParts, this.conversationId, this.mediaStore(scope),
|
|
323
|
+
this.settings.capture.media, { cache: this.outputMedia, pending });
|
|
324
|
+
return { ...record, content };
|
|
325
|
+
}));
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
private async persistMessagesWithParts(
|
|
329
|
+
records: readonly NewConversationRecord[],
|
|
330
|
+
parts: readonly (readonly ResolvedPart[] | undefined)[],
|
|
331
|
+
audit = true,
|
|
332
|
+
): Promise<readonly ConversationRecord[]> {
|
|
333
|
+
const persisted: ConversationRecord[] = [];
|
|
334
|
+
const pending: Array<readonly [object, string]> = [];
|
|
335
|
+
await this.agent.persistence.transaction(async (scope) => {
|
|
336
|
+
const prepared = await this.withStoredParts(scope, records, parts, pending);
|
|
337
|
+
await this.persistObservationsInTransaction(scope, prepared, audit, persisted);
|
|
338
|
+
});
|
|
339
|
+
for (const [part, ref] of pending) this.outputMedia.set(part, ref);
|
|
340
|
+
this.agent.publishCommittedRecords(persisted);
|
|
341
|
+
if (audit && this.settings.auditLog) this.agent.audit?.notifyPending();
|
|
342
|
+
return persisted;
|
|
226
343
|
}
|
|
227
344
|
|
|
228
345
|
async meteringRecorded(record: OperationMeteringRecord): Promise<void> {
|
|
@@ -28,7 +28,8 @@ import {
|
|
|
28
28
|
type NormalizedAgentObservation,
|
|
29
29
|
type ResolvedAgentAuditLogConfig,
|
|
30
30
|
} from "../audit/index.ts";
|
|
31
|
-
import {
|
|
31
|
+
import { conversationErrorDetailsFromError } from "../persistence/error-records.ts";
|
|
32
|
+
import { captureMessageContent } from "../media/capture.ts";
|
|
32
33
|
|
|
33
34
|
|
|
34
35
|
import type { Agent } from "../agent.ts";
|
|
@@ -72,6 +73,10 @@ export async function persistConversationObservations(
|
|
|
72
73
|
): Promise<readonly ConversationRecord[]> {
|
|
73
74
|
if (records.length === 0) return Object.freeze([]);
|
|
74
75
|
if ((!audit || !settings.auditLog) && records.every((record) => {
|
|
76
|
+
if (record.kind === "message") {
|
|
77
|
+
// Media blocks are recorded under the media level, whatever the message level.
|
|
78
|
+
return settings.capture.message === "none" && settings.capture.media === "none" && typeof record.content === "string";
|
|
79
|
+
}
|
|
75
80
|
if (record.kind !== "protocol") return settings.capture[record.kind] === "none";
|
|
76
81
|
return settings.capture.protocol.level === "none"
|
|
77
82
|
|| !shouldCaptureProtocolMethod(settings.capture.protocol, record.method);
|
|
@@ -96,12 +101,15 @@ export async function persistObservationsInTransaction(
|
|
|
96
101
|
const level = record.kind === "protocol"
|
|
97
102
|
? settings.capture.protocol.level
|
|
98
103
|
: settings.capture[record.kind];
|
|
99
|
-
const
|
|
104
|
+
const captured = captureRuntimeRecord(record, level);
|
|
105
|
+
const hasMedia = captured.kind === "message" && Array.isArray(captured.content)
|
|
106
|
+
&& captured.content.some((block) => block.type === "media");
|
|
107
|
+
const canonicalAccepted = (level !== "none" || hasMedia) && (
|
|
100
108
|
record.kind !== "protocol"
|
|
101
109
|
|| shouldCaptureProtocolMethod(settings.capture.protocol, record.method)
|
|
102
110
|
);
|
|
103
111
|
if (canonicalAccepted) {
|
|
104
|
-
persisted.push(await persistence.records.append(
|
|
112
|
+
persisted.push(await persistence.records.append(captured));
|
|
105
113
|
}
|
|
106
114
|
if (audit && settings.auditLog) {
|
|
107
115
|
await enqueueAuditObservation(persistence, {
|
|
@@ -139,6 +147,9 @@ export function captureRuntimeRecord(
|
|
|
139
147
|
record: NewConversationRecord,
|
|
140
148
|
level: RecordCaptureLevel,
|
|
141
149
|
): NewConversationRecord {
|
|
150
|
+
if (record.kind === "message") {
|
|
151
|
+
return { ...record, content: captureMessageContent(record.content, level === "content" || level === "raw") };
|
|
152
|
+
}
|
|
142
153
|
if (record.kind === "error") {
|
|
143
154
|
// `metadata` omits the display message and details; `content` keeps the message but
|
|
144
155
|
// still omits details; `raw` retains the allow-listed details.
|
|
@@ -150,8 +161,6 @@ export function captureRuntimeRecord(
|
|
|
150
161
|
}
|
|
151
162
|
if (level !== "metadata") return record;
|
|
152
163
|
switch (record.kind) {
|
|
153
|
-
case "message":
|
|
154
|
-
return { ...record, content: "" };
|
|
155
164
|
case "tool_call":
|
|
156
165
|
return {
|
|
157
166
|
recordId: record.recordId,
|
|
@@ -159,6 +168,7 @@ export function captureRuntimeRecord(
|
|
|
159
168
|
agentConversationId: record.agentConversationId,
|
|
160
169
|
kind: record.kind,
|
|
161
170
|
timestamp: record.timestamp,
|
|
171
|
+
...(record.operationId ? { operationId: record.operationId } : {}),
|
|
162
172
|
...(record.metadata ? { metadata: record.metadata } : {}),
|
|
163
173
|
toolCallId: record.toolCallId,
|
|
164
174
|
state: record.state,
|
|
@@ -171,6 +181,7 @@ export function captureRuntimeRecord(
|
|
|
171
181
|
agentConversationId: record.agentConversationId,
|
|
172
182
|
kind: record.kind,
|
|
173
183
|
timestamp: record.timestamp,
|
|
184
|
+
...(record.operationId ? { operationId: record.operationId } : {}),
|
|
174
185
|
...(record.metadata ? { metadata: record.metadata } : {}),
|
|
175
186
|
permissionId: record.permissionId,
|
|
176
187
|
state: record.state,
|
|
@@ -188,6 +199,7 @@ export function captureRuntimeRecord(
|
|
|
188
199
|
case "activity":
|
|
189
200
|
return { ...record, content: undefined, data: undefined };
|
|
190
201
|
case "metering":
|
|
202
|
+
case "cancellation":
|
|
191
203
|
return record;
|
|
192
204
|
}
|
|
193
205
|
}
|
|
@@ -216,19 +228,7 @@ export async function enqueueAuditObservation(
|
|
|
216
228
|
}
|
|
217
229
|
|
|
218
230
|
/** Allow-listed machine-readable detail from a raw ACP error, when it exposes any. */
|
|
219
|
-
export
|
|
220
|
-
const value = typeof error === "object" && error !== null
|
|
221
|
-
? error as { code?: unknown; data?: unknown }
|
|
222
|
-
: null;
|
|
223
|
-
const data = typeof value?.data === "object" && value.data !== null
|
|
224
|
-
? value.data as Record<string, unknown>
|
|
225
|
-
: undefined;
|
|
226
|
-
return buildConversationErrorDetails({
|
|
227
|
-
rpcCode: typeof value?.code === "number" ? value.code : undefined,
|
|
228
|
-
service: data?.service,
|
|
229
|
-
providerCode: data?.providerCode,
|
|
230
|
-
});
|
|
231
|
-
}
|
|
231
|
+
export const providerSessionErrorDetails = conversationErrorDetailsFromError;
|
|
232
232
|
|
|
233
233
|
export function operationIdFromMetadata(metadata: string | undefined): string | undefined {
|
|
234
234
|
if (!metadata) return undefined;
|
|
@@ -56,7 +56,9 @@ function ownAdapter(adapter: Adapter): Adapter {
|
|
|
56
56
|
if (!adapter.command.length || adapter.command.some((part) => !part)) {
|
|
57
57
|
throw new Error("adapter command must contain non-empty arguments");
|
|
58
58
|
}
|
|
59
|
+
if (adapter.cancelGraceMs !== undefined && (!Number.isFinite(adapter.cancelGraceMs) || adapter.cancelGraceMs <= 0)) throw new Error("cancelGraceMs must be positive and finite");
|
|
59
60
|
return Object.freeze({
|
|
61
|
+
...(adapter.cancelGraceMs === undefined ? {} : { cancelGraceMs: adapter.cancelGraceMs }),
|
|
60
62
|
command: Object.freeze([...adapter.command]) as unknown as string[],
|
|
61
63
|
...(adapter.ptyCommand
|
|
62
64
|
? { ptyCommand: Object.freeze([...adapter.ptyCommand]) as unknown as string[] }
|
package/src/agent-client.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
// exist in degraded mode.
|
|
9
9
|
|
|
10
10
|
import type { PromptResult, PromptHandlers, Attachment } from "./types.ts";
|
|
11
|
+
import type { MessagePart } from "./media/parts.ts";
|
|
11
12
|
|
|
12
13
|
export interface InterruptOptions {
|
|
13
14
|
/** Also drop any queued prompts, not just the in-flight one. */
|
|
@@ -34,12 +35,17 @@ export interface Bridgeable {
|
|
|
34
35
|
bridge(options?: BridgeOptions): Promise<void>;
|
|
35
36
|
}
|
|
36
37
|
|
|
38
|
+
export interface ClientPrompt {
|
|
39
|
+
text?: string;
|
|
40
|
+
parts?: readonly MessagePart[];
|
|
41
|
+
handlers?: PromptHandlers;
|
|
42
|
+
attachments?: Attachment[];
|
|
43
|
+
}
|
|
44
|
+
|
|
37
45
|
export interface AgentClient {
|
|
38
46
|
/** Send a prompt and resolve with the turn result. The main entry point. */
|
|
39
47
|
prompt(
|
|
40
|
-
|
|
41
|
-
handlers?: PromptHandlers,
|
|
42
|
-
attachments?: Attachment[],
|
|
48
|
+
input: ClientPrompt,
|
|
43
49
|
): Promise<PromptResult>;
|
|
44
50
|
|
|
45
51
|
/** Cancel the in-flight prompt; the pending prompt() resolves with status "cancelled". */
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { OperationActivity } from "./operations/contracts.ts";
|
|
1
2
|
import type { AgentMode } from "./controller.ts";
|
|
2
3
|
import type { MessageEvent, PendingMessageId, PromptEndedBy } from "./steering/contracts.ts";
|
|
3
4
|
import type { Adapter } from "./adapters.ts";
|
|
@@ -27,6 +28,9 @@ export type AgentSessionPhase =
|
|
|
27
28
|
|
|
28
29
|
/** Authoritative, immutable point-in-time state for orchestration consumers. */
|
|
29
30
|
export interface AgentSessionState {
|
|
31
|
+
readonly operation: OperationActivity | null;
|
|
32
|
+
readonly pendingHold: { readonly failedTurnId: string } | null;
|
|
33
|
+
readonly providerConnection: "connected" | "disconnected" | "reconnecting";
|
|
30
34
|
readonly phase: AgentSessionPhase;
|
|
31
35
|
/** True only while an operation is executing; queued work is reported separately. */
|
|
32
36
|
readonly isBusy: boolean;
|
|
@@ -201,6 +205,8 @@ export interface HandoffResult {
|
|
|
201
205
|
|
|
202
206
|
/** Conversation-owned lifecycle events. Harness activity remains in PromptHandlers.onActivity. */
|
|
203
207
|
export type AgentSessionEvent =
|
|
208
|
+
| { kind: "provider_reconnected"; via: "loaded" | "recovered" | "fresh"; internalSessionId: string }
|
|
209
|
+
| { kind: "operation_stage_changed"; activity: OperationActivity }
|
|
204
210
|
| { kind: "state_changed"; state: AgentSessionState }
|
|
205
211
|
| { kind: "turn_started"; turnId: string }
|
|
206
212
|
| { kind: "turn_completed"; turnId: string; result: PromptResult }
|
|
@@ -3,15 +3,19 @@ import type { Adapter } from "./adapters.ts";
|
|
|
3
3
|
import type { AgentMode } from "./controller.ts";
|
|
4
4
|
import type { NewConversationRecord, ParticipantRef, PersistenceJsonValue } from "./persistence/backend.ts";
|
|
5
5
|
import type { AgentSessionPromptResult } from "./agent-conversation-contracts.ts";
|
|
6
|
-
import type {
|
|
6
|
+
import type { CombinedMessage } from "./steering/contracts.ts";
|
|
7
7
|
import type { ResponseMessage } from "./types.ts";
|
|
8
8
|
import type { OperationMeteringRecord } from "./metering/record.ts";
|
|
9
9
|
import type { AgentSessionMeteringState } from "./metering/state.ts";
|
|
10
10
|
import type { IdentityDeliveryReceipt } from "./identity.ts";
|
|
11
|
+
import type { OperationStalledError } from "./operations/errors.ts";
|
|
11
12
|
import type {
|
|
12
13
|
ProviderAttachmentCommitAcknowledgement,
|
|
13
14
|
ProviderAttachmentState,
|
|
14
15
|
} from "./persistence/provider-attachment.ts";
|
|
16
|
+
import type { MediaCapabilities } from "./media/acp.ts";
|
|
17
|
+
import type { MessagePart, ResolvedPart } from "./media/parts.ts";
|
|
18
|
+
import type { Attachment } from "./types.ts";
|
|
15
19
|
|
|
16
20
|
export interface OwnedPromptInput {
|
|
17
21
|
readonly operationId: string;
|
|
@@ -21,19 +25,38 @@ export interface OwnedPromptInput {
|
|
|
21
25
|
readonly participantId?: string;
|
|
22
26
|
readonly consumerMetadata?: PersistenceJsonValue;
|
|
23
27
|
/** Present when several messages were combined into this one prompt: each is recorded as sent. */
|
|
24
|
-
readonly parts?: readonly
|
|
28
|
+
readonly parts?: readonly CombinedMessage[];
|
|
25
29
|
readonly text: string;
|
|
30
|
+
readonly messageParts?: readonly MessagePart[];
|
|
31
|
+
readonly attachments?: readonly Attachment[];
|
|
32
|
+
/** What the parts are resolved against: the working directory, and what the agent accepts. */
|
|
33
|
+
readonly mediaContext?: {
|
|
34
|
+
readonly cwd: string;
|
|
35
|
+
readonly capabilities?: MediaCapabilities;
|
|
36
|
+
readonly degraded?: boolean;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** How a turn's assistant messages ended, for its commit. */
|
|
41
|
+
interface OwnedPromptMessageEnds {
|
|
42
|
+
/**
|
|
43
|
+
* When each message that ended before the turn did (the next message or a tool call began)
|
|
44
|
+
* received its last text, in order. Those messages are completed at these times; the rest take
|
|
45
|
+
* the turn's outcome.
|
|
46
|
+
*/
|
|
47
|
+
readonly messageEnds?: readonly string[];
|
|
26
48
|
}
|
|
27
49
|
|
|
28
50
|
export interface OwnedPromptPreparation {
|
|
29
|
-
|
|
51
|
+
/** The parts to send: the user's, wrapped with the provider-only text (identity, out-of-band). */
|
|
52
|
+
readonly providerParts?: readonly ResolvedPart[];
|
|
30
53
|
readonly participant?: ParticipantRef;
|
|
31
54
|
/** Every participant of a combined prompt, in order. `participant` is the first. */
|
|
32
55
|
readonly participants?: readonly ParticipantRef[];
|
|
33
56
|
readonly identityDeliveryReceipt?: IdentityDeliveryReceipt;
|
|
34
57
|
}
|
|
35
58
|
|
|
36
|
-
export interface OwnedPromptCompleted extends OwnedPromptInput {
|
|
59
|
+
export interface OwnedPromptCompleted extends OwnedPromptInput, OwnedPromptMessageEnds {
|
|
37
60
|
readonly result: AgentSessionPromptResult;
|
|
38
61
|
readonly identityDeliveryReceipt?: IdentityDeliveryReceipt;
|
|
39
62
|
readonly providerAttachment: ProviderAttachmentState;
|
|
@@ -54,13 +77,15 @@ export class OwnedPromptPostCommitError extends Error {
|
|
|
54
77
|
}
|
|
55
78
|
}
|
|
56
79
|
|
|
57
|
-
export interface OwnedPromptFailed extends OwnedPromptInput {
|
|
80
|
+
export interface OwnedPromptFailed extends OwnedPromptInput, OwnedPromptMessageEnds {
|
|
58
81
|
readonly messages: readonly ResponseMessage[];
|
|
59
82
|
readonly error: unknown;
|
|
60
83
|
}
|
|
61
84
|
|
|
62
85
|
/** @internal Agent-owned persistence and identity boundary for a conversation turn. */
|
|
63
86
|
export interface AgentConversationOwnerLifecycle {
|
|
87
|
+
operationFailed?(input: { readonly operationId: string; readonly error: OperationStalledError }): Promise<void>;
|
|
88
|
+
recoverInPlace?(error: unknown): Promise<void>;
|
|
64
89
|
beforePrompt(input: OwnedPromptInput): Promise<OwnedPromptPreparation>;
|
|
65
90
|
/** The participant that history imported from an adopted provider session is attributed to. */
|
|
66
91
|
importParticipant?(): Promise<ParticipantRef>;
|
|
@@ -83,5 +108,5 @@ export interface AgentConversationOwnerLifecycle {
|
|
|
83
108
|
readonly activatedAt: string;
|
|
84
109
|
}): Promise<void>;
|
|
85
110
|
/** Append a typed non-message runtime observation under the owner's capture policy. */
|
|
86
|
-
record?(record: NewConversationRecord): Promise<void>;
|
|
111
|
+
record?(record: NewConversationRecord, parts?: readonly ResolvedPart[]): Promise<void>;
|
|
87
112
|
}
|
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
} from "./activity.ts";
|
|
7
7
|
import type { Logger } from "./logger.ts";
|
|
8
8
|
import { persistenceEventFromActivity } from "./persistence/activity-projection.ts";
|
|
9
|
+
import type { NormalizedPersistenceEvent } from "./persistence/projection.ts";
|
|
9
10
|
import {
|
|
10
11
|
presentationItemFromRecord,
|
|
11
12
|
type TranscriptPresentationItem,
|
|
@@ -111,11 +112,21 @@ export class AgentConversationPresentation {
|
|
|
111
112
|
});
|
|
112
113
|
}
|
|
113
114
|
|
|
115
|
+
/** Append a non-presentation event in the same order as the presentation writes. */
|
|
116
|
+
queueEvent(event: NormalizedPersistenceEvent): void {
|
|
117
|
+
this.#presentationWrite = this.#presentationWrite.then(async () => {
|
|
118
|
+
await this.#persistence()?.appendEvent(event);
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
114
122
|
emitPersistedRecord(
|
|
115
123
|
record: Awaited<ReturnType<PersistenceStateRuntime["appendPresentationEvent"]>>,
|
|
116
124
|
): void {
|
|
117
125
|
if (!record) return;
|
|
118
|
-
const
|
|
126
|
+
const id = record.presentation?.id;
|
|
127
|
+
// Later revisions report when the item began; the runtime keeps that while its operation runs.
|
|
128
|
+
const startedAt = id === undefined ? undefined : this.#persistence()?.presentationStartedAt?.(id);
|
|
129
|
+
const item = presentationItemFromRecord(record, startedAt);
|
|
119
130
|
if (item) this.#onPresentation(item);
|
|
120
131
|
}
|
|
121
132
|
|
|
@@ -52,7 +52,7 @@ export class AgentConversationQueue<T> {
|
|
|
52
52
|
* Drain every item serially. Concurrent calls share the active drain; an item
|
|
53
53
|
* enqueued by an active operation is observed by the same loop.
|
|
54
54
|
*/
|
|
55
|
-
drain(execute: (item: T) => Promise<void
|
|
55
|
+
drain(execute: (item: T) => Promise<void>, select?: () => T | undefined): Promise<void> {
|
|
56
56
|
if (this.#activeDrain) return this.#activeDrain;
|
|
57
57
|
this.#draining = true;
|
|
58
58
|
let resolveDrain!: () => void;
|
|
@@ -67,7 +67,8 @@ export class AgentConversationQueue<T> {
|
|
|
67
67
|
void (async () => {
|
|
68
68
|
try {
|
|
69
69
|
while (this.#items.length > 0) {
|
|
70
|
-
const item = this.#items.shift()
|
|
70
|
+
const item = select ? select() : this.#items.shift();
|
|
71
|
+
if (item === undefined) break;
|
|
71
72
|
await execute(item);
|
|
72
73
|
}
|
|
73
74
|
} finally {
|