@qlairoslabs/acp-client 0.10.1 → 0.11.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/CONSUMER_GUIDE.md +252 -0
- package/README.md +0 -3
- package/package.json +1 -1
- package/src/agent/adoption/config.ts +57 -0
- package/src/agent/adoption/index.ts +8 -0
- package/src/agent/adoption/provider-session-delete.ts +27 -0
- package/src/agent/adoption/provider-sessions.ts +73 -0
- package/src/agent/adoption/recap.ts +15 -0
- package/src/agent/adoption/replay.ts +84 -0
- package/src/agent/config.ts +182 -0
- package/src/agent/conversation-manager.ts +1006 -0
- package/src/agent/manager-settings.ts +46 -0
- package/src/agent/persisted-lifecycle.ts +309 -0
- package/src/agent/persistence-policy/index.ts +8 -0
- package/src/agent/persistence-policy/resolver.ts +118 -0
- package/src/agent/persistence-policy/types.ts +50 -0
- package/src/agent/record-capture.ts +243 -0
- package/src/agent-conversation-contracts.ts +11 -0
- package/src/agent-conversation-errors.ts +24 -0
- package/src/agent-conversation-owner.ts +7 -0
- package/src/agent-conversation-queue.ts +23 -0
- package/src/agent-session.ts +236 -66
- package/src/agent.ts +63 -1223
- package/src/audit/config.ts +29 -0
- package/src/audit/index.ts +1 -0
- package/src/checkpointing/contracts.ts +2 -0
- package/src/checkpointing/persistence/sqlite-repository.ts +13 -0
- package/src/checkpointing/strategy.ts +11 -5
- package/src/client.ts +25 -2
- package/src/controller.ts +3 -0
- package/src/index.ts +24 -0
- package/src/internal-inference/contracts.ts +23 -0
- package/src/internal-inference/coordination/manager.ts +22 -8
- package/src/persistence/backend.ts +17 -0
- package/src/persistence/sqlite-backend.ts +30 -4
- package/src/persistence/sqlite-provider-sessions.ts +35 -0
- package/src/persistence/sqlite-schema.ts +13 -3
- package/src/steering/combine.ts +56 -0
- package/src/steering/contracts.ts +84 -0
- package/src/steering/controller.ts +205 -0
- package/src/steering/index.ts +14 -0
- package/src/transport/acp-transport.ts +11 -0
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type AgentConversationId,
|
|
3
|
+
} from "../agent-ids.ts";
|
|
4
|
+
import {
|
|
5
|
+
type IdentityConsistency,
|
|
6
|
+
} from "../identity.ts";
|
|
7
|
+
import {
|
|
8
|
+
type ConversationRecord,
|
|
9
|
+
type ConversationRecordCaptureConfig,
|
|
10
|
+
type ConversationRecordCapturePolicy,
|
|
11
|
+
type MeteringRecordRetention,
|
|
12
|
+
} from "../persistence/backend.ts";
|
|
13
|
+
import {
|
|
14
|
+
type AgentAuditCaptureConfig,
|
|
15
|
+
type ResolvedAgentAuditLogConfig,
|
|
16
|
+
} from "../audit/index.ts";
|
|
17
|
+
import {
|
|
18
|
+
type ResolvedConversationCheckpointingConfig,
|
|
19
|
+
} from "../checkpointing/index.ts";
|
|
20
|
+
|
|
21
|
+
import type {
|
|
22
|
+
AgentConversationRuntimeDefaults,
|
|
23
|
+
} from "./config.ts";
|
|
24
|
+
import type { ConversationPersistenceResolver } from "./persistence-policy/types.ts";
|
|
25
|
+
|
|
26
|
+
export interface ManagerSettings {
|
|
27
|
+
readonly defaultAdapterId?: string;
|
|
28
|
+
readonly identityConsistency: IdentityConsistency;
|
|
29
|
+
readonly identityTimeoutMs?: number;
|
|
30
|
+
/** The Agent's resolved capture. A conversation's own settings replace it (see persistence-policy). */
|
|
31
|
+
readonly capture: ConversationRecordCapturePolicy;
|
|
32
|
+
/** The Agent's capture as configured, which per-conversation overrides are layered over. */
|
|
33
|
+
readonly captureConfig?: ConversationRecordCaptureConfig;
|
|
34
|
+
/** The Agent's audit capture as configured, which per-conversation audit overrides are layered over. */
|
|
35
|
+
readonly auditCaptureConfig?: AgentAuditCaptureConfig;
|
|
36
|
+
/** The consumer's per-conversation resolver, if any. */
|
|
37
|
+
readonly conversationPersistence?: ConversationPersistenceResolver;
|
|
38
|
+
readonly defaults: AgentConversationRuntimeDefaults;
|
|
39
|
+
readonly meteringRecords: MeteringRecordRetention;
|
|
40
|
+
readonly checkpointing: ResolvedConversationCheckpointingConfig | null;
|
|
41
|
+
readonly auditLog: ResolvedAgentAuditLogConfig | null;
|
|
42
|
+
readonly auditIdentityUpdate: (
|
|
43
|
+
agentConversationId: AgentConversationId,
|
|
44
|
+
records: readonly ConversationRecord[],
|
|
45
|
+
) => Promise<void>;
|
|
46
|
+
}
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
type AgentConversationId,
|
|
4
|
+
} from "../agent-ids.ts";
|
|
5
|
+
import type { AgentMode } from "../controller.ts";
|
|
6
|
+
import type { OperationMeteringRecord } from "../metering/record.ts";
|
|
7
|
+
import type { AgentSessionMeteringState } from "../metering/state.ts";
|
|
8
|
+
import {
|
|
9
|
+
IMPLICIT_USER_PARTICIPANT_ID,
|
|
10
|
+
type ConversationRecord,
|
|
11
|
+
type NewConversationRecord,
|
|
12
|
+
type ParticipantRef,
|
|
13
|
+
type PersistenceScope,
|
|
14
|
+
} from "../persistence/backend.ts";
|
|
15
|
+
import type {
|
|
16
|
+
AgentConversationOwnerLifecycle,
|
|
17
|
+
OwnedPromptCommitResult,
|
|
18
|
+
OwnedPromptCompleted,
|
|
19
|
+
OwnedPromptFailed,
|
|
20
|
+
OwnedPromptInput,
|
|
21
|
+
} from "../agent-conversation-owner.ts";
|
|
22
|
+
import { OwnedPromptPostCommitError } from "../agent-conversation-owner.ts";
|
|
23
|
+
import {
|
|
24
|
+
composeProviderPrompt,
|
|
25
|
+
pendingOutOfBandMessages,
|
|
26
|
+
} from "../out-of-band-messages.ts";
|
|
27
|
+
import type {
|
|
28
|
+
ProviderAttachmentCommitAcknowledgement,
|
|
29
|
+
} from "../persistence/provider-attachment.ts";
|
|
30
|
+
|
|
31
|
+
import type { ManagerSettings } from "./manager-settings.ts";
|
|
32
|
+
import {
|
|
33
|
+
updateConversationIdentity,
|
|
34
|
+
persistConversationObservations,
|
|
35
|
+
persistObservationsInTransaction,
|
|
36
|
+
captureRuntimeRecord,
|
|
37
|
+
enqueueAuditObservation,
|
|
38
|
+
} from "./record-capture.ts";
|
|
39
|
+
|
|
40
|
+
import type { Agent } from "../agent.ts";
|
|
41
|
+
|
|
42
|
+
export class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle {
|
|
43
|
+
constructor(
|
|
44
|
+
private readonly agent: Agent,
|
|
45
|
+
private readonly conversationId: AgentConversationId,
|
|
46
|
+
private readonly initialParticipants: readonly ParticipantRef[],
|
|
47
|
+
private readonly settings: ManagerSettings,
|
|
48
|
+
) {}
|
|
49
|
+
|
|
50
|
+
async beforePrompt(input: OwnedPromptInput) {
|
|
51
|
+
// A combined prompt records each original message as it was sent, under the same operation.
|
|
52
|
+
const parts = input.parts ?? [{
|
|
53
|
+
id: input.operationId,
|
|
54
|
+
text: input.text,
|
|
55
|
+
...(input.participantId ? { participantId: input.participantId } : {}),
|
|
56
|
+
...(input.consumerMetadata !== undefined ? { consumerMetadata: input.consumerMetadata } : {}),
|
|
57
|
+
}];
|
|
58
|
+
const participants: ParticipantRef[] = [];
|
|
59
|
+
for (const part of parts) participants.push(await this.resolveParticipant(part.participantId));
|
|
60
|
+
const participant = participants[0]!;
|
|
61
|
+
const identity = await this.agent.identity.load({
|
|
62
|
+
agentSessionId: this.agent.id,
|
|
63
|
+
agentConversationId: this.conversationId,
|
|
64
|
+
targetProviderContextId: input.targetProviderContextId,
|
|
65
|
+
participant,
|
|
66
|
+
prompt: input.text,
|
|
67
|
+
consistency: this.settings.identityConsistency,
|
|
68
|
+
...(this.settings.identityTimeoutMs !== undefined
|
|
69
|
+
? { timeoutMs: this.settings.identityTimeoutMs }
|
|
70
|
+
: {}),
|
|
71
|
+
});
|
|
72
|
+
const records = await this.appendMessages(parts.map((part, index): NewConversationRecord => ({
|
|
73
|
+
recordId: index === 0 ? `${input.operationId}:user` : `${input.operationId}:user:${index + 1}`,
|
|
74
|
+
agentSessionId: this.agent.id,
|
|
75
|
+
agentConversationId: this.conversationId,
|
|
76
|
+
kind: "message",
|
|
77
|
+
timestamp: new Date().toISOString(),
|
|
78
|
+
role: "user",
|
|
79
|
+
participantId: participants[index]!.id,
|
|
80
|
+
...(part.consumerMetadata !== undefined ? { consumerMetadata: part.consumerMetadata } : {}),
|
|
81
|
+
content: part.text,
|
|
82
|
+
status: "completed",
|
|
83
|
+
metadata: JSON.stringify({ operationId: input.operationId }),
|
|
84
|
+
})));
|
|
85
|
+
await this.updateIdentity(records);
|
|
86
|
+
// Read after the user record commits so a concurrent append falls in this turn or the next.
|
|
87
|
+
const outOfBand = records[0]
|
|
88
|
+
? await pendingOutOfBandMessages(
|
|
89
|
+
this.agent.persistence,
|
|
90
|
+
this.conversationId,
|
|
91
|
+
input.targetProviderContextId,
|
|
92
|
+
records[0].sequence,
|
|
93
|
+
)
|
|
94
|
+
: [];
|
|
95
|
+
return Object.freeze({
|
|
96
|
+
providerText: composeProviderPrompt(input.text, identity.promptPreamble, outOfBand),
|
|
97
|
+
participant,
|
|
98
|
+
participants: Object.freeze(participants),
|
|
99
|
+
...(identity.deliveryReceipt ? { identityDeliveryReceipt: identity.deliveryReceipt } : {}),
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async afterPrompt(input: OwnedPromptCompleted): Promise<OwnedPromptCommitResult> {
|
|
104
|
+
const timestamp = new Date().toISOString();
|
|
105
|
+
const status = input.result.status === "error" ? "failed" : input.result.status;
|
|
106
|
+
const records = input.result.messages.map((message, index): NewConversationRecord => ({
|
|
107
|
+
recordId: `${input.operationId}:assistant:${index + 1}`,
|
|
108
|
+
agentSessionId: this.agent.id,
|
|
109
|
+
agentConversationId: this.conversationId,
|
|
110
|
+
kind: "message",
|
|
111
|
+
timestamp,
|
|
112
|
+
role: "assistant",
|
|
113
|
+
logicalMessageId: `message:${input.operationId}:assistant:${index + 1}`,
|
|
114
|
+
content: message.text,
|
|
115
|
+
status,
|
|
116
|
+
metadata: JSON.stringify({
|
|
117
|
+
operationId: input.operationId,
|
|
118
|
+
...(message.messageId ? { providerMessageId: message.messageId } : {}),
|
|
119
|
+
}),
|
|
120
|
+
}));
|
|
121
|
+
const persisted: ConversationRecord[] = [];
|
|
122
|
+
let providerAttachment: ProviderAttachmentCommitAcknowledgement | undefined;
|
|
123
|
+
await this.agent.persistence.transaction(async (persistence) => {
|
|
124
|
+
await this.persistObservationsInTransaction(persistence, records, true, persisted);
|
|
125
|
+
if (status === "completed" && input.providerAttachment.kind === "runtime_only") {
|
|
126
|
+
const descriptor = input.providerAttachment.descriptor;
|
|
127
|
+
const providerSessionRecordId = `provider-${randomUUID()}`;
|
|
128
|
+
await persistence.identityDelivery?.reset(
|
|
129
|
+
this.conversationId,
|
|
130
|
+
descriptor.internalSessionId,
|
|
131
|
+
);
|
|
132
|
+
await persistence.providerSessions.append({
|
|
133
|
+
providerSessionRecordId,
|
|
134
|
+
agentConversationId: this.conversationId,
|
|
135
|
+
internalSessionId: descriptor.internalSessionId,
|
|
136
|
+
adapterId: descriptor.adapterId,
|
|
137
|
+
mode: descriptor.mode,
|
|
138
|
+
...(descriptor.model ? { model: descriptor.model } : {}),
|
|
139
|
+
activatedAt: descriptor.acquiredAt,
|
|
140
|
+
...(descriptor.transitionId ? { transitionId: descriptor.transitionId } : {}),
|
|
141
|
+
});
|
|
142
|
+
providerAttachment = Object.freeze({
|
|
143
|
+
attachmentAttemptId: descriptor.attachmentAttemptId,
|
|
144
|
+
providerSessionRecordId,
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
this.agent.publishCommittedRecords(persisted);
|
|
149
|
+
if (this.settings.auditLog) this.agent.audit?.notifyPending();
|
|
150
|
+
const commit: OwnedPromptCommitResult = Object.freeze({
|
|
151
|
+
...(providerAttachment ? { providerAttachment } : {}),
|
|
152
|
+
});
|
|
153
|
+
try {
|
|
154
|
+
await this.updateIdentity(Object.freeze(persisted));
|
|
155
|
+
if (status === "completed" && input.identityDeliveryReceipt) {
|
|
156
|
+
await this.agent.identity.delivered?.(input.identityDeliveryReceipt);
|
|
157
|
+
}
|
|
158
|
+
if (status === "completed") {
|
|
159
|
+
await this.agent.checkpointing?.afterSuccessfulResponse(this.conversationId);
|
|
160
|
+
}
|
|
161
|
+
} catch (error) {
|
|
162
|
+
throw new OwnedPromptPostCommitError(commit, error);
|
|
163
|
+
}
|
|
164
|
+
return commit;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async promptFailed(input: OwnedPromptFailed): Promise<void> {
|
|
168
|
+
const timestamp = new Date().toISOString();
|
|
169
|
+
const records = input.messages.map((message, index): NewConversationRecord => ({
|
|
170
|
+
recordId: `${input.operationId}:assistant:${index + 1}`,
|
|
171
|
+
agentSessionId: this.agent.id,
|
|
172
|
+
agentConversationId: this.conversationId,
|
|
173
|
+
kind: "message",
|
|
174
|
+
timestamp,
|
|
175
|
+
role: "assistant",
|
|
176
|
+
logicalMessageId: `message:${input.operationId}:assistant:${index + 1}`,
|
|
177
|
+
content: message.text,
|
|
178
|
+
status: "failed",
|
|
179
|
+
metadata: JSON.stringify({
|
|
180
|
+
operationId: input.operationId,
|
|
181
|
+
...(message.messageId ? { providerMessageId: message.messageId } : {}),
|
|
182
|
+
}),
|
|
183
|
+
}));
|
|
184
|
+
await this.updateIdentity(await this.appendMessages(records));
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
resolveAdapter(adapterId: string) {
|
|
188
|
+
return this.agent.adapters.require(adapterId);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
async transitionActivated(input: {
|
|
192
|
+
readonly transitionId: string;
|
|
193
|
+
readonly agentConversationId: AgentConversationId;
|
|
194
|
+
readonly internalSessionId: string;
|
|
195
|
+
readonly adapterId: string;
|
|
196
|
+
readonly mode: AgentMode;
|
|
197
|
+
readonly model?: string;
|
|
198
|
+
readonly activatedAt: string;
|
|
199
|
+
}): Promise<void> {
|
|
200
|
+
await this.agent.persistence.transaction(async (persistence) => {
|
|
201
|
+
await persistence.identityDelivery?.reset(input.agentConversationId, input.internalSessionId);
|
|
202
|
+
await persistence.providerSessions.append({
|
|
203
|
+
providerSessionRecordId: `provider-${randomUUID()}`,
|
|
204
|
+
agentConversationId: input.agentConversationId,
|
|
205
|
+
internalSessionId: input.internalSessionId,
|
|
206
|
+
adapterId: input.adapterId,
|
|
207
|
+
mode: input.mode,
|
|
208
|
+
...(input.model ? { model: input.model } : {}),
|
|
209
|
+
activatedAt: input.activatedAt,
|
|
210
|
+
transitionId: input.transitionId,
|
|
211
|
+
});
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async importParticipant(): Promise<ParticipantRef> {
|
|
216
|
+
return await this.resolveParticipant();
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async record(record: NewConversationRecord): Promise<void> {
|
|
220
|
+
const streamingSnapshot = record.kind === "message" && record.status === "in_progress";
|
|
221
|
+
const persisted = await this.persistObservations([record], !streamingSnapshot);
|
|
222
|
+
// A streaming snapshot is a display revision, not a second completed response.
|
|
223
|
+
if (!streamingSnapshot) {
|
|
224
|
+
await this.updateIdentity(persisted);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async meteringRecorded(record: OperationMeteringRecord): Promise<void> {
|
|
229
|
+
const level = this.settings.capture.metering;
|
|
230
|
+
let reference: ConversationRecord | undefined;
|
|
231
|
+
await this.agent.persistence.transaction(async (persistence) => {
|
|
232
|
+
await persistence.metering.commit({
|
|
233
|
+
agentConversationId: this.conversationId,
|
|
234
|
+
record,
|
|
235
|
+
meteringRecords: this.settings.meteringRecords,
|
|
236
|
+
});
|
|
237
|
+
const timelineRecord: NewConversationRecord = {
|
|
238
|
+
recordId: `${record.operationId}:metering`,
|
|
239
|
+
agentSessionId: this.agent.id,
|
|
240
|
+
agentConversationId: this.conversationId,
|
|
241
|
+
kind: "metering",
|
|
242
|
+
timestamp: new Date(record.completedAt).toISOString(),
|
|
243
|
+
operationId: record.operationId,
|
|
244
|
+
meteringRecordId: record.operationId,
|
|
245
|
+
status: record.usage.status === "metered" ? "available" : "unavailable",
|
|
246
|
+
metadata: JSON.stringify({ operationId: record.operationId }),
|
|
247
|
+
};
|
|
248
|
+
if (level !== "none") {
|
|
249
|
+
reference = await persistence.records.append(captureRuntimeRecord(timelineRecord, level));
|
|
250
|
+
}
|
|
251
|
+
if (this.settings.auditLog) {
|
|
252
|
+
await enqueueAuditObservation(persistence, {
|
|
253
|
+
scope: "conversation",
|
|
254
|
+
sourceObservationId: timelineRecord.recordId,
|
|
255
|
+
operationId: record.operationId,
|
|
256
|
+
record: timelineRecord,
|
|
257
|
+
meteringRecord: record,
|
|
258
|
+
}, this.settings.auditLog);
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
if (reference) this.agent.publishCommittedRecords([reference]);
|
|
262
|
+
if (this.settings.auditLog) this.agent.audit?.notifyPending();
|
|
263
|
+
if (reference) await this.updateIdentity([reference]);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async meteringStateChanged(state: AgentSessionMeteringState): Promise<void> {
|
|
267
|
+
await this.agent.persistence.metering.saveState(this.conversationId, state);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
private async resolveParticipant(participantId?: string): Promise<ParticipantRef> {
|
|
271
|
+
const id = participantId
|
|
272
|
+
?? (this.initialParticipants.length === 1
|
|
273
|
+
? this.initialParticipants[0]!.id
|
|
274
|
+
: IMPLICIT_USER_PARTICIPANT_ID);
|
|
275
|
+
const existing = (await this.agent.persistence.conversations.get(this.conversationId))
|
|
276
|
+
?.participants.find((participant) => participant.id === id);
|
|
277
|
+
if (existing) return existing;
|
|
278
|
+
return await this.agent.persistence.conversations.ensureParticipant(this.conversationId, {
|
|
279
|
+
id,
|
|
280
|
+
kind: "user",
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
private async appendMessages(
|
|
285
|
+
records: readonly NewConversationRecord[],
|
|
286
|
+
): Promise<readonly ConversationRecord[]> {
|
|
287
|
+
return await this.persistObservations(records);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
private async persistObservations(
|
|
291
|
+
records: readonly NewConversationRecord[],
|
|
292
|
+
audit = true,
|
|
293
|
+
): Promise<readonly ConversationRecord[]> {
|
|
294
|
+
return await persistConversationObservations(this.agent, this.settings, records, audit);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
private async persistObservationsInTransaction(
|
|
298
|
+
persistence: PersistenceScope,
|
|
299
|
+
records: readonly NewConversationRecord[],
|
|
300
|
+
audit: boolean,
|
|
301
|
+
persisted: ConversationRecord[],
|
|
302
|
+
): Promise<void> {
|
|
303
|
+
await persistObservationsInTransaction(this.settings, persistence, records, audit, persisted);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
private async updateIdentity(records: readonly ConversationRecord[]): Promise<void> {
|
|
307
|
+
await updateConversationIdentity(this.agent, this.settings, this.conversationId, records);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { ConversationSettingsResolver } from "./resolver.ts";
|
|
2
|
+
export type {
|
|
3
|
+
AgentConversationAuditCaptureConfig,
|
|
4
|
+
AgentConversationPersistenceOverride,
|
|
5
|
+
AgentScopeAuditObservationKind,
|
|
6
|
+
ConversationPersistenceContext,
|
|
7
|
+
ConversationPersistenceResolver,
|
|
8
|
+
} from "./types.ts";
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { resolveConversationAuditConfig, type ResolvedAgentAuditLogConfig } from "../../audit/index.ts";
|
|
2
|
+
import type {
|
|
3
|
+
ConversationRecordCaptureConfig,
|
|
4
|
+
ConversationRecordCapturePolicy,
|
|
5
|
+
MeteringRecordRetention,
|
|
6
|
+
} from "../../persistence/backend.ts";
|
|
7
|
+
import { resolveConversationRecordCapture } from "../../persistence/backend.ts";
|
|
8
|
+
import type { ManagerSettings } from "../manager-settings.ts";
|
|
9
|
+
import type {
|
|
10
|
+
AgentConversationAuditCaptureConfig,
|
|
11
|
+
AgentConversationPersistenceOverride,
|
|
12
|
+
ConversationPersistenceContext,
|
|
13
|
+
ConversationPersistenceResolver,
|
|
14
|
+
} from "./types.ts";
|
|
15
|
+
|
|
16
|
+
const KNOWN_KEYS = new Set(["capture", "auditLog", "meteringRecords"]);
|
|
17
|
+
|
|
18
|
+
/** Stable JSON: object keys sorted, so equal overrides share one cache entry. */
|
|
19
|
+
function canonicalJson(value: unknown): string {
|
|
20
|
+
return JSON.stringify(value, (_key, nested) =>
|
|
21
|
+
nested && typeof nested === "object" && !Array.isArray(nested)
|
|
22
|
+
? Object.fromEntries(Object.entries(nested).sort(([a], [b]) => a.localeCompare(b)))
|
|
23
|
+
: nested);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function validMeteringRetention(value: unknown): MeteringRecordRetention {
|
|
27
|
+
if (value === "all" || value === "none") return value;
|
|
28
|
+
const retain = (value as { retain?: unknown } | null)?.retain;
|
|
29
|
+
if (typeof value === "object" && value !== null && Number.isInteger(retain) && (retain as number) >= 1) {
|
|
30
|
+
return { retain: retain as number };
|
|
31
|
+
}
|
|
32
|
+
throw new Error('invalid meteringRecords retention: use "all", "none" or { retain: n } with n >= 1');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Turns the Agent's settings and the consumer's resolver into the settings one conversation runs with.
|
|
37
|
+
*
|
|
38
|
+
* The resolver is called when a conversation starts (and for writes about a conversation that is not
|
|
39
|
+
* live). A resolver that throws, or returns something invalid, is a caller mistake: the error is
|
|
40
|
+
* thrown as it is, before any write. Identical overrides are validated and resolved once.
|
|
41
|
+
*/
|
|
42
|
+
export class ConversationSettingsResolver {
|
|
43
|
+
readonly #capture = new Map<string, ConversationRecordCapturePolicy>();
|
|
44
|
+
readonly #audit = new Map<string, ResolvedAgentAuditLogConfig>();
|
|
45
|
+
|
|
46
|
+
constructor(
|
|
47
|
+
private readonly base: ManagerSettings,
|
|
48
|
+
private readonly resolver: ConversationPersistenceResolver | undefined,
|
|
49
|
+
) {}
|
|
50
|
+
|
|
51
|
+
settingsFor(context: ConversationPersistenceContext): ManagerSettings {
|
|
52
|
+
if (!this.resolver) return this.base;
|
|
53
|
+
const override = this.resolver(context);
|
|
54
|
+
if (override === undefined) return this.base;
|
|
55
|
+
this.#validateShape(override);
|
|
56
|
+
|
|
57
|
+
const capture = override.capture !== undefined && Object.keys(override.capture).length > 0
|
|
58
|
+
? this.#resolveCapture(override.capture)
|
|
59
|
+
: undefined;
|
|
60
|
+
const auditLog = override.auditLog === undefined ? undefined : this.#resolveAudit(override.auditLog);
|
|
61
|
+
const meteringRecords = override.meteringRecords === undefined
|
|
62
|
+
? undefined
|
|
63
|
+
: validMeteringRetention(override.meteringRecords);
|
|
64
|
+
|
|
65
|
+
if (capture === undefined && auditLog === undefined && meteringRecords === undefined) return this.base;
|
|
66
|
+
return {
|
|
67
|
+
...this.base,
|
|
68
|
+
...(capture ? { capture } : {}),
|
|
69
|
+
...(auditLog !== undefined ? { auditLog } : {}),
|
|
70
|
+
...(meteringRecords !== undefined ? { meteringRecords } : {}),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
#validateShape(override: AgentConversationPersistenceOverride): void {
|
|
75
|
+
if (override === null || typeof override !== "object" || Array.isArray(override)) {
|
|
76
|
+
throw new Error("conversation persistence resolver must return an object or undefined");
|
|
77
|
+
}
|
|
78
|
+
for (const key of Object.keys(override)) {
|
|
79
|
+
if (!KNOWN_KEYS.has(key)) throw new Error(`unknown conversation persistence override key: ${key}`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
#resolveCapture(override: ConversationRecordCaptureConfig): ConversationRecordCapturePolicy {
|
|
84
|
+
const key = canonicalJson(override);
|
|
85
|
+
const cached = this.#capture.get(key);
|
|
86
|
+
if (cached) return cached;
|
|
87
|
+
// Per key: the override replaces the Agent's value; `protocol` is one key, so its level and method
|
|
88
|
+
// filters are replaced together.
|
|
89
|
+
const resolved = resolveConversationRecordCapture({ ...this.base.captureConfig, ...override });
|
|
90
|
+
// Checkpoints over messages stored as metadata would summarize empty text, and identity would deliver
|
|
91
|
+
// empty lines. `none` is fine: such a conversation simply has nothing to checkpoint.
|
|
92
|
+
if (this.base.checkpointing?.enabled && resolved.message === "metadata") {
|
|
93
|
+
throw new Error(
|
|
94
|
+
'conversation checkpointing is enabled: message capture "metadata" would checkpoint empty messages',
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
this.#capture.set(key, resolved);
|
|
98
|
+
return resolved;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** `null` takes the conversation out of the audit stream; a configuration changes what it records there. */
|
|
102
|
+
#resolveAudit(
|
|
103
|
+
override: false | { readonly capture?: AgentConversationAuditCaptureConfig },
|
|
104
|
+
): ResolvedAgentAuditLogConfig | null | undefined {
|
|
105
|
+
if (override === false) return null;
|
|
106
|
+
if (override === null || typeof override !== "object" || Array.isArray(override)) {
|
|
107
|
+
throw new Error("conversation auditLog override must be false or an object");
|
|
108
|
+
}
|
|
109
|
+
if (!this.base.auditLog) throw new Error("conversation audit capture requires an Agent audit log");
|
|
110
|
+
if (override.capture === undefined || Object.keys(override.capture).length === 0) return undefined;
|
|
111
|
+
const key = canonicalJson(override.capture);
|
|
112
|
+
const cached = this.#audit.get(key);
|
|
113
|
+
if (cached) return cached;
|
|
114
|
+
const resolved = resolveConversationAuditConfig(this.base.auditLog, this.base.auditCaptureConfig, override.capture);
|
|
115
|
+
this.#audit.set(key, resolved);
|
|
116
|
+
return resolved;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { AgentConversationId } from "../../agent-ids.ts";
|
|
2
|
+
import type { AgentAuditCaptureConfig, NormalizedAgentLevelObservation } from "../../audit/index.ts";
|
|
3
|
+
import type {
|
|
4
|
+
ConversationRecordCaptureConfig,
|
|
5
|
+
MeteringRecordRetention,
|
|
6
|
+
ParticipantRef,
|
|
7
|
+
} from "../../persistence/backend.ts";
|
|
8
|
+
|
|
9
|
+
/** Audit kinds observed at agent scope; they cannot be tuned per conversation. */
|
|
10
|
+
export type AgentScopeAuditObservationKind = NormalizedAgentLevelObservation["kind"];
|
|
11
|
+
|
|
12
|
+
export type AgentConversationAuditCaptureConfig = Omit<AgentAuditCaptureConfig, AgentScopeAuditObservationKind>;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* What one conversation persists differently from the Agent defaults. Keys it sets replace the Agent's
|
|
16
|
+
* values; keys it omits follow the Agent. `undefined` and `{}` both mean "use the Agent defaults".
|
|
17
|
+
*
|
|
18
|
+
*/
|
|
19
|
+
export interface AgentConversationPersistenceOverride {
|
|
20
|
+
/** Canonical record capture. Keys set here replace the Agent's; omitted keys inherit. */
|
|
21
|
+
readonly capture?: ConversationRecordCaptureConfig;
|
|
22
|
+
/**
|
|
23
|
+
* `false` keeps this conversation out of the audit stream entirely: no entry about it, none caused by its
|
|
24
|
+
* records. An object changes what its audit entries capture (agent-scope kinds cannot be tuned per
|
|
25
|
+
* conversation). Requires the Agent to have an audit log.
|
|
26
|
+
*/
|
|
27
|
+
readonly auditLog?: false | { readonly capture?: AgentConversationAuditCaptureConfig };
|
|
28
|
+
/** Detailed metering-record retention for this conversation (`"all"`, `"none"` or `{ retain: n }`). */
|
|
29
|
+
readonly meteringRecords?: MeteringRecordRetention;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** What the library knows about a conversation when it asks for its policy. */
|
|
33
|
+
export interface ConversationPersistenceContext {
|
|
34
|
+
readonly agentConversationId: AgentConversationId;
|
|
35
|
+
readonly participants: readonly ParticipantRef[];
|
|
36
|
+
readonly title?: string;
|
|
37
|
+
readonly metadata?: string;
|
|
38
|
+
/** True when the conversation was created by adopting an existing provider session. */
|
|
39
|
+
readonly adopted: boolean;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Chooses what a conversation persists. It runs when a conversation starts and whenever a write about a
|
|
44
|
+
* conversation that is not live needs its policy, so it must be synchronous, free of side effects and
|
|
45
|
+
* stable for a given conversation. The library infers nothing: what a conversation *is* stays the
|
|
46
|
+
* consumer's business.
|
|
47
|
+
*/
|
|
48
|
+
export type ConversationPersistenceResolver = (
|
|
49
|
+
conversation: ConversationPersistenceContext,
|
|
50
|
+
) => AgentConversationPersistenceOverride | undefined;
|