@qlairoslabs/acp-client 0.7.4 → 0.9.2
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-audit.md +58 -0
- package/CONSUMER_GUIDE.md +571 -19
- package/package.json +6 -1
- package/src/agent-adapter-registry.ts +66 -0
- package/src/agent-conversation-continuation.ts +121 -0
- package/src/agent-conversation-contracts.ts +279 -0
- package/src/agent-conversation-errors.ts +31 -0
- package/src/agent-conversation-owner.ts +60 -0
- package/src/agent-conversation-presentation.ts +217 -0
- package/src/agent-conversation-queue.ts +44 -0
- package/src/agent-conversation.ts +41 -0
- package/src/agent-ids.ts +50 -0
- package/src/agent-session.ts +1032 -674
- package/src/agent.ts +1223 -0
- package/src/audit/config.ts +186 -0
- package/src/audit/contracts.ts +59 -0
- package/src/audit/index.ts +50 -0
- package/src/audit/projection.ts +127 -0
- package/src/audit/reader.ts +371 -0
- package/src/audit/runtime.ts +1060 -0
- package/src/checkpointing/config.ts +91 -0
- package/src/checkpointing/contracts.ts +45 -0
- package/src/checkpointing/coordinator.ts +100 -0
- package/src/checkpointing/ids.ts +5 -0
- package/src/checkpointing/index.ts +6 -0
- package/src/checkpointing/persistence/sqlite-repository.ts +159 -0
- package/src/checkpointing/recovery.ts +114 -0
- package/src/checkpointing/strategy.ts +139 -0
- package/src/identity/checkpoint-backed.ts +248 -0
- package/src/identity.ts +76 -0
- package/src/index.ts +132 -0
- package/src/internal-inference/config.ts +68 -0
- package/src/internal-inference/contracts.ts +218 -0
- package/src/internal-inference/coordination/handles.ts +133 -0
- package/src/internal-inference/coordination/manager.ts +487 -0
- package/src/internal-inference/ids.ts +10 -0
- package/src/internal-inference/index.ts +10 -0
- package/src/internal-inference/persistence/records.ts +132 -0
- package/src/internal-inference/persistence/repository.ts +35 -0
- package/src/internal-inference/persistence/sqlite-repository.ts +551 -0
- package/src/internal-inference/runtime/harness-runtime.ts +78 -0
- package/src/internal-inference/strategy/registry.ts +42 -0
- package/src/metering/engine.ts +47 -0
- package/src/metering/record.ts +4 -1
- package/src/observation/contracts.ts +10 -0
- package/src/observation/index.ts +8 -0
- package/src/observation/subscription-hub.ts +43 -0
- package/src/persistence/activity-projection.ts +26 -12
- package/src/persistence/backend.ts +839 -0
- package/src/persistence/index.ts +113 -0
- package/src/persistence/sqlite-backend.ts +2192 -0
- package/src/persistence/sqlite-conversation-records.ts +430 -0
- package/src/persistence/sqlite-owner-lock.ts +106 -0
- package/src/persistence/sqlite-schema.ts +589 -0
- package/src/persistence/timeline-reconcile.ts +72 -0
package/src/agent.ts
ADDED
|
@@ -0,0 +1,1223 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import type * as schema from "@agentclientprotocol/sdk";
|
|
3
|
+
import {
|
|
4
|
+
createAgentConversationId,
|
|
5
|
+
type AgentConversationId,
|
|
6
|
+
type AgentSessionId,
|
|
7
|
+
} from "./agent-ids.ts";
|
|
8
|
+
import {
|
|
9
|
+
AgentAdapterRegistry,
|
|
10
|
+
type AgentAdapterRegistration,
|
|
11
|
+
} from "./agent-adapter-registry.ts";
|
|
12
|
+
import {
|
|
13
|
+
AgentConversation,
|
|
14
|
+
type AgentConversationConfig,
|
|
15
|
+
} from "./agent-session.ts";
|
|
16
|
+
import type { AgentMode } from "./controller.ts";
|
|
17
|
+
import type { OperationMeteringRecord } from "./metering/record.ts";
|
|
18
|
+
import type { MeteredOperationKind } from "./metering/record.ts";
|
|
19
|
+
import { MeteringEngine } from "./metering/engine.ts";
|
|
20
|
+
import { createModelsDevResolver } from "./metering/catalog/index.ts";
|
|
21
|
+
import type { AgentSessionMeteringState } from "./metering/state.ts";
|
|
22
|
+
import {
|
|
23
|
+
NoopAgentIdentityRuntime,
|
|
24
|
+
composeIdentityPrompt,
|
|
25
|
+
type AgentIdentityRuntime,
|
|
26
|
+
type IdentityConsistency,
|
|
27
|
+
} from "./identity.ts";
|
|
28
|
+
import {
|
|
29
|
+
CheckpointBackedIdentityRuntime,
|
|
30
|
+
type CheckpointBackedIdentityConfig,
|
|
31
|
+
} from "./identity/checkpoint-backed.ts";
|
|
32
|
+
import {
|
|
33
|
+
IMPLICIT_USER_PARTICIPANT_ID,
|
|
34
|
+
PersistenceCapabilityError,
|
|
35
|
+
normalizeParticipantRef,
|
|
36
|
+
resolveConversationRecordCapture,
|
|
37
|
+
shouldCaptureProtocolMethod,
|
|
38
|
+
type AgentConversationSummary,
|
|
39
|
+
type ConversationListOptions,
|
|
40
|
+
type ConversationPage,
|
|
41
|
+
type ConversationPreviewPage,
|
|
42
|
+
type ConversationRecord,
|
|
43
|
+
type ConversationRecordCaptureConfig,
|
|
44
|
+
type ConversationRecordCapturePolicy,
|
|
45
|
+
type MeteringRecordRetention,
|
|
46
|
+
type NewConversationRecord,
|
|
47
|
+
type ParticipantRef,
|
|
48
|
+
type PersistenceBackend,
|
|
49
|
+
type PersistenceExtension,
|
|
50
|
+
type PersistenceScope,
|
|
51
|
+
type RecordCaptureLevel,
|
|
52
|
+
} from "./persistence/backend.ts";
|
|
53
|
+
import { SqliteAgentPersistence } from "./persistence/sqlite-backend.ts";
|
|
54
|
+
import {
|
|
55
|
+
projectAgentAuditObservation,
|
|
56
|
+
resolveAgentAuditLogConfig,
|
|
57
|
+
AgentAuditRuntime,
|
|
58
|
+
type AgentAuditLogConfig,
|
|
59
|
+
type NormalizedAgentObservation,
|
|
60
|
+
type ResolvedAgentAuditLogConfig,
|
|
61
|
+
} from "./audit/index.ts";
|
|
62
|
+
import type {
|
|
63
|
+
AgentConversationOwnerLifecycle,
|
|
64
|
+
OwnedPromptCompleted,
|
|
65
|
+
OwnedPromptFailed,
|
|
66
|
+
OwnedPromptInput,
|
|
67
|
+
} from "./agent-conversation-owner.ts";
|
|
68
|
+
import {
|
|
69
|
+
resolveInternalInferenceConfig,
|
|
70
|
+
type InternalInferenceConfig,
|
|
71
|
+
} from "./internal-inference/config.ts";
|
|
72
|
+
import type {
|
|
73
|
+
InternalInferenceManager,
|
|
74
|
+
InternalInferenceStrategy,
|
|
75
|
+
} from "./internal-inference/contracts.ts";
|
|
76
|
+
import { DefaultInternalInferenceManager } from "./internal-inference/coordination/manager.ts";
|
|
77
|
+
import type { InternalInferenceSnapshot } from "./internal-inference/contracts.ts";
|
|
78
|
+
import { HarnessInternalInferenceRuntime } from "./internal-inference/runtime/harness-runtime.ts";
|
|
79
|
+
import {
|
|
80
|
+
ConversationCheckpointCoordinator,
|
|
81
|
+
ConversationCheckpointStrategy,
|
|
82
|
+
CONVERSATION_CHECKPOINT_STRATEGY_ID,
|
|
83
|
+
buildRecoverySeed,
|
|
84
|
+
isMissingProviderSessionError,
|
|
85
|
+
resolveConversationCheckpointingConfig,
|
|
86
|
+
type ConversationCheckpointingConfig,
|
|
87
|
+
type ConversationRecoveryProgress,
|
|
88
|
+
type ConversationRecoveryResult,
|
|
89
|
+
type ResolvedConversationCheckpointingConfig,
|
|
90
|
+
} from "./checkpointing/index.ts";
|
|
91
|
+
|
|
92
|
+
export type AgentPersistenceConfig =
|
|
93
|
+
| {
|
|
94
|
+
readonly kind: "sqlite";
|
|
95
|
+
readonly path: string;
|
|
96
|
+
readonly metadata?: string;
|
|
97
|
+
readonly busyTimeoutMs?: number;
|
|
98
|
+
readonly extensions?: readonly PersistenceExtension[];
|
|
99
|
+
readonly allowUnsafeWalVersion?: boolean;
|
|
100
|
+
}
|
|
101
|
+
| { readonly kind: "custom"; readonly backend: PersistenceBackend };
|
|
102
|
+
|
|
103
|
+
type OwnerControlledConversationKey =
|
|
104
|
+
| "adapter"
|
|
105
|
+
| "adapterId"
|
|
106
|
+
| "agentSessionId"
|
|
107
|
+
| "agentConversationId"
|
|
108
|
+
| "ownerAgentSessionId"
|
|
109
|
+
| "participants"
|
|
110
|
+
| "ownerLifecycle"
|
|
111
|
+
| "providerSession"
|
|
112
|
+
| "persistence"
|
|
113
|
+
| "transcriptPath"
|
|
114
|
+
| "transcriptDir"
|
|
115
|
+
| "sessions";
|
|
116
|
+
|
|
117
|
+
export type AgentConversationRuntimeDefaults = Omit<
|
|
118
|
+
AgentConversationConfig,
|
|
119
|
+
OwnerControlledConversationKey
|
|
120
|
+
>;
|
|
121
|
+
|
|
122
|
+
export interface AgentConfig {
|
|
123
|
+
readonly id?: AgentSessionId;
|
|
124
|
+
readonly persistence: AgentPersistenceConfig;
|
|
125
|
+
readonly adapters: Readonly<Record<string, import("./adapters.ts").Adapter>>
|
|
126
|
+
| readonly AgentAdapterRegistration[];
|
|
127
|
+
readonly defaultAdapterId?: string;
|
|
128
|
+
readonly identity?: AgentIdentityRuntime | CheckpointBackedIdentityConfig;
|
|
129
|
+
readonly identityConsistency?: IdentityConsistency;
|
|
130
|
+
readonly identityTimeoutMs?: number;
|
|
131
|
+
readonly capture?: ConversationRecordCaptureConfig;
|
|
132
|
+
readonly conversationDefaults?: AgentConversationRuntimeDefaults;
|
|
133
|
+
/** Bounded metering state is always persisted; this controls detailed local history. */
|
|
134
|
+
readonly meteringPersistence?: {
|
|
135
|
+
readonly meteringRecords?: MeteringRecordRetention;
|
|
136
|
+
};
|
|
137
|
+
readonly internalInference?: InternalInferenceConfig & {
|
|
138
|
+
readonly strategies?: readonly InternalInferenceStrategy[];
|
|
139
|
+
};
|
|
140
|
+
readonly checkpointing?: ConversationCheckpointingConfig;
|
|
141
|
+
readonly auditLog?: false | AgentAuditLogConfig;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export interface CreateAgentConversationConfig {
|
|
145
|
+
readonly id?: AgentConversationId;
|
|
146
|
+
readonly adapterId?: string;
|
|
147
|
+
readonly mode?: AgentMode;
|
|
148
|
+
readonly participants?: readonly ParticipantRef[];
|
|
149
|
+
readonly title?: string;
|
|
150
|
+
readonly metadata?: string;
|
|
151
|
+
readonly mcpServers?: schema.McpServer[];
|
|
152
|
+
readonly runtime?: AgentConversationRuntimeDefaults;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export interface OpenAgentConversationConfig {
|
|
156
|
+
readonly adapterId?: string;
|
|
157
|
+
readonly mode?: AgentMode;
|
|
158
|
+
readonly mcpServers?: schema.McpServer[];
|
|
159
|
+
readonly runtime?: AgentConversationRuntimeDefaults;
|
|
160
|
+
readonly onRecoveryProgress?: (event: ConversationRecoveryProgress) => void;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export interface OpenOwnedAgentConversationResult {
|
|
164
|
+
readonly conversation: AgentConversation;
|
|
165
|
+
readonly providerSession: "already_open" | "loaded" | "new" | "recovered";
|
|
166
|
+
readonly recovery?: ConversationRecoveryResult;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export interface AgentConversationManager {
|
|
170
|
+
create(config?: CreateAgentConversationConfig): Promise<AgentConversation>;
|
|
171
|
+
open(
|
|
172
|
+
id: AgentConversationId,
|
|
173
|
+
config?: OpenAgentConversationConfig,
|
|
174
|
+
): Promise<OpenOwnedAgentConversationResult>;
|
|
175
|
+
get(id: AgentConversationId): Promise<AgentConversationSummary | null>;
|
|
176
|
+
list(options?: ConversationListOptions): Promise<ConversationPage>;
|
|
177
|
+
listPreviews(options?: ConversationListOptions): Promise<ConversationPreviewPage>;
|
|
178
|
+
delete(id: AgentConversationId, deletedAt?: string): Promise<void>;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Durable owner of one agent identity, its adapters, identity runtime, and conversations. */
|
|
182
|
+
export class Agent {
|
|
183
|
+
readonly id: AgentSessionId;
|
|
184
|
+
readonly persistence: PersistenceBackend;
|
|
185
|
+
readonly identity: AgentIdentityRuntime;
|
|
186
|
+
readonly adapters: AgentAdapterRegistry;
|
|
187
|
+
readonly conversations: AgentConversationManager;
|
|
188
|
+
readonly internalInferences?: InternalInferenceManager;
|
|
189
|
+
readonly checkpointing?: ConversationCheckpointCoordinator;
|
|
190
|
+
readonly audit?: AgentAuditRuntime;
|
|
191
|
+
|
|
192
|
+
private readonly manager: DefaultAgentConversationManager;
|
|
193
|
+
private auditObservationTail: Promise<void> = Promise.resolve();
|
|
194
|
+
private auditObservationError: unknown;
|
|
195
|
+
private detachInternalInferenceAudit?: () => void;
|
|
196
|
+
private closed = false;
|
|
197
|
+
|
|
198
|
+
private constructor(
|
|
199
|
+
id: AgentSessionId,
|
|
200
|
+
persistence: PersistenceBackend,
|
|
201
|
+
identity: AgentIdentityRuntime | CheckpointBackedIdentityConfig | undefined,
|
|
202
|
+
adapters: AgentAdapterRegistry,
|
|
203
|
+
config: AgentConfig,
|
|
204
|
+
private readonly auditLog: ResolvedAgentAuditLogConfig | null,
|
|
205
|
+
audit: AgentAuditRuntime | undefined,
|
|
206
|
+
) {
|
|
207
|
+
this.id = id;
|
|
208
|
+
this.persistence = persistence;
|
|
209
|
+
this.adapters = adapters;
|
|
210
|
+
this.audit = audit;
|
|
211
|
+
const checkpointing = config.checkpointing
|
|
212
|
+
? resolveConversationCheckpointingConfig(config.checkpointing)
|
|
213
|
+
: null;
|
|
214
|
+
const checkpointBackedIdentity = identity && !("load" in identity) && identity.kind === "checkpoint-backed"
|
|
215
|
+
? identity
|
|
216
|
+
: null;
|
|
217
|
+
if (identity && !("load" in identity) && !checkpointBackedIdentity) {
|
|
218
|
+
throw new Error("unknown built-in identity configuration");
|
|
219
|
+
}
|
|
220
|
+
if (checkpointBackedIdentity) {
|
|
221
|
+
if (!checkpointing?.enabled) {
|
|
222
|
+
throw new Error("checkpoint-backed identity requires enabled conversation checkpointing");
|
|
223
|
+
}
|
|
224
|
+
if (!persistence.identityDelivery || !persistence.recoveryCheckpoints) {
|
|
225
|
+
throw new Error("checkpoint-backed identity requires delivery cursor persistence");
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
this.identity = checkpointBackedIdentity
|
|
229
|
+
? new CheckpointBackedIdentityRuntime(
|
|
230
|
+
persistence,
|
|
231
|
+
checkpointBackedIdentity,
|
|
232
|
+
async (source) => { await this.checkpointing?.request(source); },
|
|
233
|
+
)
|
|
234
|
+
: identity && "load" in identity
|
|
235
|
+
? identity
|
|
236
|
+
: new NoopAgentIdentityRuntime();
|
|
237
|
+
this.manager = new DefaultAgentConversationManager(this, {
|
|
238
|
+
defaultAdapterId: config.defaultAdapterId,
|
|
239
|
+
identityConsistency: config.identityConsistency ?? "eventual",
|
|
240
|
+
identityTimeoutMs: config.identityTimeoutMs,
|
|
241
|
+
capture: resolveConversationRecordCapture(config.capture),
|
|
242
|
+
defaults: config.conversationDefaults ?? {},
|
|
243
|
+
meteringRecords: config.meteringPersistence?.meteringRecords ?? "all",
|
|
244
|
+
checkpointing,
|
|
245
|
+
auditLog,
|
|
246
|
+
auditIdentityUpdate: async (agentConversationId, records) => {
|
|
247
|
+
if (records.length === 0) return;
|
|
248
|
+
await this.recordAgentAuditObservation("identity", "updated", {
|
|
249
|
+
agentConversationId,
|
|
250
|
+
sourceRecordIds: records.map((record) => record.recordId),
|
|
251
|
+
}, `identity:${records.map((record) => record.recordId).join(":")}`);
|
|
252
|
+
},
|
|
253
|
+
});
|
|
254
|
+
this.conversations = this.manager;
|
|
255
|
+
if (checkpointing?.enabled) {
|
|
256
|
+
const messageCapture = resolveConversationRecordCapture(config.capture).message;
|
|
257
|
+
if (messageCapture !== "content" && messageCapture !== "raw") {
|
|
258
|
+
throw new Error("conversation checkpointing requires message capture at content or raw level");
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
if (config.internalInference || checkpointing?.enabled) {
|
|
262
|
+
const inferenceConfig = config.internalInference ?? {};
|
|
263
|
+
const settings = resolveInternalInferenceConfig(inferenceConfig);
|
|
264
|
+
if (!persistence.internalInferences) {
|
|
265
|
+
throw new Error("persistence backend does not support internal inference");
|
|
266
|
+
}
|
|
267
|
+
const runtime = settings.runtime ?? new HarnessInternalInferenceRuntime({
|
|
268
|
+
controllerConfig: (request) => ({
|
|
269
|
+
adapter: adapters.require(request.adapterId),
|
|
270
|
+
adapterId: request.adapterId,
|
|
271
|
+
...(config.conversationDefaults?.launcher
|
|
272
|
+
? { launcher: config.conversationDefaults.launcher }
|
|
273
|
+
: {}),
|
|
274
|
+
...(config.conversationDefaults?.execPrefix
|
|
275
|
+
? { execPrefix: config.conversationDefaults.execPrefix }
|
|
276
|
+
: {}),
|
|
277
|
+
...(config.conversationDefaults?.env ? { env: config.conversationDefaults.env } : {}),
|
|
278
|
+
...(config.conversationDefaults?.cwd ? { cwd: config.conversationDefaults.cwd } : {}),
|
|
279
|
+
...(config.conversationDefaults?.clientInfo
|
|
280
|
+
? { clientInfo: config.conversationDefaults.clientInfo }
|
|
281
|
+
: {}),
|
|
282
|
+
...(config.conversationDefaults?.clientCapabilities
|
|
283
|
+
? { clientCapabilities: config.conversationDefaults.clientCapabilities }
|
|
284
|
+
: {}),
|
|
285
|
+
...(config.conversationDefaults?.logger
|
|
286
|
+
? { logger: config.conversationDefaults.logger }
|
|
287
|
+
: {}),
|
|
288
|
+
...(config.conversationDefaults?.wire ? { wire: config.conversationDefaults.wire } : {}),
|
|
289
|
+
}),
|
|
290
|
+
});
|
|
291
|
+
const strategies = [...(inferenceConfig.strategies ?? [])];
|
|
292
|
+
if (checkpointing?.enabled) {
|
|
293
|
+
if (strategies.some((strategy) =>
|
|
294
|
+
strategy.purpose === "conversation_checkpoint"
|
|
295
|
+
&& strategy.strategyId === CONVERSATION_CHECKPOINT_STRATEGY_ID
|
|
296
|
+
&& strategy.version === 1)) {
|
|
297
|
+
throw new Error("the built-in conversation checkpoint strategy is already registered");
|
|
298
|
+
}
|
|
299
|
+
strategies.push(new ConversationCheckpointStrategy());
|
|
300
|
+
}
|
|
301
|
+
this.internalInferences = new DefaultInternalInferenceManager({
|
|
302
|
+
agentSessionId: id,
|
|
303
|
+
repository: persistence.internalInferences,
|
|
304
|
+
persistence,
|
|
305
|
+
runtime,
|
|
306
|
+
settings,
|
|
307
|
+
strategies,
|
|
308
|
+
meteringRecords: config.meteringPersistence?.meteringRecords ?? "all",
|
|
309
|
+
beginMetering: async (attempt, session) => {
|
|
310
|
+
return await this.manager.beginInternalInferenceMetering(attempt, session);
|
|
311
|
+
},
|
|
312
|
+
resolveAdapterId: async (requestedAdapterId, agentConversationId) => {
|
|
313
|
+
if (requestedAdapterId) {
|
|
314
|
+
adapters.require(requestedAdapterId);
|
|
315
|
+
return requestedAdapterId;
|
|
316
|
+
}
|
|
317
|
+
if (settings.adapter !== "same") {
|
|
318
|
+
adapters.require(settings.adapter);
|
|
319
|
+
return settings.adapter;
|
|
320
|
+
}
|
|
321
|
+
if (agentConversationId) {
|
|
322
|
+
const active = await persistence.providerSessions.active(agentConversationId);
|
|
323
|
+
if (active) {
|
|
324
|
+
adapters.require(active.adapterId);
|
|
325
|
+
return active.adapterId;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
const fallback = config.defaultAdapterId ?? adapters.list()[0]?.id;
|
|
329
|
+
if (!fallback) throw new Error("internal inference could not resolve an adapter");
|
|
330
|
+
adapters.require(fallback);
|
|
331
|
+
return fallback;
|
|
332
|
+
},
|
|
333
|
+
});
|
|
334
|
+
if (auditLog) {
|
|
335
|
+
this.detachInternalInferenceAudit = this.internalInferences.subscribe((event) => {
|
|
336
|
+
this.queueAgentAuditObservation(
|
|
337
|
+
"internal_inference",
|
|
338
|
+
event.snapshot.stage,
|
|
339
|
+
event.snapshot as unknown as import("./persistence/backend.ts").PersistenceJsonValue,
|
|
340
|
+
`internal-inference:${event.inferenceId}:${event.sequence}`,
|
|
341
|
+
event.inferenceId,
|
|
342
|
+
);
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
if (checkpointing?.enabled) {
|
|
346
|
+
this.checkpointing = new ConversationCheckpointCoordinator(
|
|
347
|
+
persistence,
|
|
348
|
+
this.internalInferences,
|
|
349
|
+
checkpointing,
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
static async open(config: AgentConfig): Promise<Agent> {
|
|
356
|
+
const auditLog = config.auditLog && resolveAgentAuditLogConfig(config.auditLog);
|
|
357
|
+
if (auditLog && config.persistence.kind === "custom") {
|
|
358
|
+
throw new PersistenceCapabilityError("auditOutbox");
|
|
359
|
+
}
|
|
360
|
+
const registrations = Array.isArray(config.adapters)
|
|
361
|
+
? config.adapters
|
|
362
|
+
: Object.entries(config.adapters).map(([id, adapter]) => ({ id, adapter }));
|
|
363
|
+
const adapters = new AgentAdapterRegistry(registrations);
|
|
364
|
+
if (adapters.list().length === 0) throw new Error("Agent requires at least one adapter");
|
|
365
|
+
if (config.defaultAdapterId) adapters.require(config.defaultAdapterId);
|
|
366
|
+
|
|
367
|
+
let persistence: PersistenceBackend;
|
|
368
|
+
let id: AgentSessionId;
|
|
369
|
+
if (config.persistence.kind === "custom") {
|
|
370
|
+
persistence = config.persistence.backend;
|
|
371
|
+
id = config.id ?? persistence.identityRecord.agentSessionId;
|
|
372
|
+
if (persistence.identityRecord.agentSessionId !== id) {
|
|
373
|
+
throw new Error(
|
|
374
|
+
`custom persistence belongs to ${persistence.identityRecord.agentSessionId}, not ${id}`,
|
|
375
|
+
);
|
|
376
|
+
}
|
|
377
|
+
} else {
|
|
378
|
+
persistence = await SqliteAgentPersistence.open({
|
|
379
|
+
path: config.persistence.path,
|
|
380
|
+
...(config.id ? { agentSessionId: config.id } : {}),
|
|
381
|
+
...(config.persistence.metadata !== undefined ? { metadata: config.persistence.metadata } : {}),
|
|
382
|
+
...(config.persistence.busyTimeoutMs !== undefined
|
|
383
|
+
? { busyTimeoutMs: config.persistence.busyTimeoutMs }
|
|
384
|
+
: {}),
|
|
385
|
+
...(config.persistence.extensions ? { extensions: config.persistence.extensions } : {}),
|
|
386
|
+
...(config.persistence.allowUnsafeWalVersion !== undefined
|
|
387
|
+
? { allowUnsafeWalVersion: config.persistence.allowUnsafeWalVersion }
|
|
388
|
+
: {}),
|
|
389
|
+
});
|
|
390
|
+
id = persistence.identityRecord.agentSessionId;
|
|
391
|
+
}
|
|
392
|
+
let audit: AgentAuditRuntime | undefined;
|
|
393
|
+
try {
|
|
394
|
+
if (auditLog) {
|
|
395
|
+
if (!persistence.auditOutbox) throw new PersistenceCapabilityError("auditOutbox");
|
|
396
|
+
const state = await persistence.auditOutbox.state();
|
|
397
|
+
const initialized = await persistence.auditOutbox.initialize(
|
|
398
|
+
state?.auditLogId ?? `audlog-${randomUUID()}`,
|
|
399
|
+
auditLog.captureFingerprint,
|
|
400
|
+
);
|
|
401
|
+
audit = await AgentAuditRuntime.open({
|
|
402
|
+
persistence,
|
|
403
|
+
agentSessionId: id,
|
|
404
|
+
config: auditLog,
|
|
405
|
+
auditState: initialized,
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
const agent = new Agent(
|
|
409
|
+
id,
|
|
410
|
+
persistence,
|
|
411
|
+
config.identity,
|
|
412
|
+
adapters,
|
|
413
|
+
config,
|
|
414
|
+
auditLog || null,
|
|
415
|
+
audit,
|
|
416
|
+
);
|
|
417
|
+
await agent.recordAgentAuditObservation("agent_lifecycle", "opened");
|
|
418
|
+
return agent;
|
|
419
|
+
} catch (error) {
|
|
420
|
+
await audit?.close().catch(() => undefined);
|
|
421
|
+
await persistence.close().catch(() => undefined);
|
|
422
|
+
throw error;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
static async create(config: AgentConfig): Promise<Agent> {
|
|
427
|
+
return await Agent.open(config);
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
async close(): Promise<void> {
|
|
431
|
+
if (this.closed) return;
|
|
432
|
+
this.closed = true;
|
|
433
|
+
let shutdownError: unknown;
|
|
434
|
+
try {
|
|
435
|
+
this.checkpointing?.close();
|
|
436
|
+
await (this.internalInferences as DefaultInternalInferenceManager | undefined)?.close();
|
|
437
|
+
this.detachInternalInferenceAudit?.();
|
|
438
|
+
this.detachInternalInferenceAudit = undefined;
|
|
439
|
+
await this.auditObservationTail;
|
|
440
|
+
const observationError = this.auditObservationError;
|
|
441
|
+
await this.manager.stopAll();
|
|
442
|
+
await this.recordAgentAuditObservation("agent_lifecycle", "closed");
|
|
443
|
+
if (observationError !== undefined) throw observationError;
|
|
444
|
+
} catch (error) {
|
|
445
|
+
shutdownError = error;
|
|
446
|
+
}
|
|
447
|
+
const cleanupErrors: unknown[] = [];
|
|
448
|
+
try {
|
|
449
|
+
await this.audit?.close();
|
|
450
|
+
} catch (error) {
|
|
451
|
+
cleanupErrors.push(error);
|
|
452
|
+
}
|
|
453
|
+
try {
|
|
454
|
+
await this.persistence.close();
|
|
455
|
+
} catch (error) {
|
|
456
|
+
cleanupErrors.push(error);
|
|
457
|
+
}
|
|
458
|
+
if (shutdownError !== undefined) cleanupErrors.unshift(shutdownError);
|
|
459
|
+
if (cleanupErrors.length === 1) throw cleanupErrors[0];
|
|
460
|
+
if (cleanupErrors.length > 1) throw new AggregateError(cleanupErrors, "agent shutdown failed");
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
private async recordAgentAuditObservation(
|
|
464
|
+
kind: "agent_lifecycle" | "identity" | "internal_inference",
|
|
465
|
+
state: string,
|
|
466
|
+
payload?: import("./persistence/backend.ts").PersistenceJsonValue,
|
|
467
|
+
sourceObservationId = `${kind}-${randomUUID()}`,
|
|
468
|
+
operationId?: string,
|
|
469
|
+
): Promise<void> {
|
|
470
|
+
const auditLog = this.auditLog;
|
|
471
|
+
if (!auditLog) return;
|
|
472
|
+
await enqueueAuditObservation(this.persistence, {
|
|
473
|
+
scope: "agent",
|
|
474
|
+
sourceObservationId,
|
|
475
|
+
agentSessionId: this.id,
|
|
476
|
+
kind,
|
|
477
|
+
occurredAt: new Date().toISOString(),
|
|
478
|
+
state,
|
|
479
|
+
...(operationId ? { operationId } : {}),
|
|
480
|
+
...(payload !== undefined ? { payload } : {}),
|
|
481
|
+
}, auditLog);
|
|
482
|
+
this.audit?.notifyPending();
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
private queueAgentAuditObservation(
|
|
486
|
+
kind: "agent_lifecycle" | "identity" | "internal_inference",
|
|
487
|
+
state: string,
|
|
488
|
+
payload?: import("./persistence/backend.ts").PersistenceJsonValue,
|
|
489
|
+
sourceObservationId?: string,
|
|
490
|
+
operationId?: string,
|
|
491
|
+
): void {
|
|
492
|
+
const write = this.auditObservationTail.then(() => this.recordAgentAuditObservation(
|
|
493
|
+
kind,
|
|
494
|
+
state,
|
|
495
|
+
payload,
|
|
496
|
+
sourceObservationId,
|
|
497
|
+
operationId,
|
|
498
|
+
));
|
|
499
|
+
this.auditObservationTail = write.catch((error) => {
|
|
500
|
+
if (this.auditObservationError === undefined) this.auditObservationError = error;
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
interface ManagerSettings {
|
|
506
|
+
readonly defaultAdapterId?: string;
|
|
507
|
+
readonly identityConsistency: IdentityConsistency;
|
|
508
|
+
readonly identityTimeoutMs?: number;
|
|
509
|
+
readonly capture: ConversationRecordCapturePolicy;
|
|
510
|
+
readonly defaults: AgentConversationRuntimeDefaults;
|
|
511
|
+
readonly meteringRecords: MeteringRecordRetention;
|
|
512
|
+
readonly checkpointing: ResolvedConversationCheckpointingConfig | null;
|
|
513
|
+
readonly auditLog: ResolvedAgentAuditLogConfig | null;
|
|
514
|
+
readonly auditIdentityUpdate: (
|
|
515
|
+
agentConversationId: AgentConversationId,
|
|
516
|
+
records: readonly ConversationRecord[],
|
|
517
|
+
) => Promise<void>;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
class DefaultAgentConversationManager implements AgentConversationManager {
|
|
521
|
+
private readonly live = new Map<AgentConversationId, AgentConversation>();
|
|
522
|
+
private readonly openings = new Map<AgentConversationId, Promise<OpenOwnedAgentConversationResult>>();
|
|
523
|
+
private readonly meteringSetupLocks = new Map<AgentConversationId, Promise<void>>();
|
|
524
|
+
private readonly detachedMeteringBarriers = new Map<AgentConversationId, Promise<void>>();
|
|
525
|
+
private agentMeteringBarrier: Promise<void> | undefined;
|
|
526
|
+
|
|
527
|
+
constructor(private readonly agent: Agent, private readonly settings: ManagerSettings) {}
|
|
528
|
+
|
|
529
|
+
async create(config: CreateAgentConversationConfig = {}): Promise<AgentConversation> {
|
|
530
|
+
const id = config.id ?? createAgentConversationId();
|
|
531
|
+
const participants = normalizeParticipants(config.participants);
|
|
532
|
+
await this.agent.persistence.conversations.create({
|
|
533
|
+
agentSessionId: this.agent.id,
|
|
534
|
+
agentConversationId: id,
|
|
535
|
+
participants,
|
|
536
|
+
...(config.title !== undefined ? { title: config.title } : {}),
|
|
537
|
+
...(config.metadata !== undefined ? { metadata: config.metadata } : {}),
|
|
538
|
+
});
|
|
539
|
+
return await this.start(id, participants, {
|
|
540
|
+
...config,
|
|
541
|
+
providerSession: "new",
|
|
542
|
+
});
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
async open(
|
|
546
|
+
id: AgentConversationId,
|
|
547
|
+
config: OpenAgentConversationConfig = {},
|
|
548
|
+
): Promise<OpenOwnedAgentConversationResult> {
|
|
549
|
+
const existing = this.live.get(id);
|
|
550
|
+
if (existing && existing.state.phase !== "stopped") {
|
|
551
|
+
return Object.freeze({ conversation: existing, providerSession: "already_open" });
|
|
552
|
+
}
|
|
553
|
+
const pending = this.openings.get(id);
|
|
554
|
+
if (pending) return await pending;
|
|
555
|
+
const opening = this.openOnce(id, config);
|
|
556
|
+
this.openings.set(id, opening);
|
|
557
|
+
try {
|
|
558
|
+
return await opening;
|
|
559
|
+
} finally {
|
|
560
|
+
if (this.openings.get(id) === opening) this.openings.delete(id);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
private async openOnce(
|
|
565
|
+
id: AgentConversationId,
|
|
566
|
+
config: OpenAgentConversationConfig,
|
|
567
|
+
): Promise<OpenOwnedAgentConversationResult> {
|
|
568
|
+
const summary = await this.agent.persistence.conversations.get(id);
|
|
569
|
+
if (!summary || summary.deletedAt) throw new Error(`unknown active conversation: ${id}`);
|
|
570
|
+
const active = await this.agent.persistence.providerSessions.active(id);
|
|
571
|
+
if (active && config.adapterId && config.adapterId !== active.adapterId) {
|
|
572
|
+
throw new Error(
|
|
573
|
+
`conversation ${id} is active on ${active.adapterId}; use a conversation switch instead of loading it with ${config.adapterId}`,
|
|
574
|
+
);
|
|
575
|
+
}
|
|
576
|
+
const startConfig = {
|
|
577
|
+
...config,
|
|
578
|
+
runtime: {
|
|
579
|
+
...(summary.title ? { title: summary.title } : {}),
|
|
580
|
+
...config.runtime,
|
|
581
|
+
},
|
|
582
|
+
adapterId: config.adapterId ?? active?.adapterId,
|
|
583
|
+
};
|
|
584
|
+
try {
|
|
585
|
+
const conversation = await this.start(id, summary.participants, {
|
|
586
|
+
...startConfig,
|
|
587
|
+
providerSession: active ? "load" : "new",
|
|
588
|
+
internalSessionId: active?.internalSessionId,
|
|
589
|
+
});
|
|
590
|
+
return Object.freeze({
|
|
591
|
+
conversation,
|
|
592
|
+
providerSession: active ? "loaded" : "new",
|
|
593
|
+
});
|
|
594
|
+
} catch (error) {
|
|
595
|
+
const recovery = this.settings.checkpointing?.recovery;
|
|
596
|
+
if (
|
|
597
|
+
!active
|
|
598
|
+
|| recovery?.onLoadFailure !== "recover"
|
|
599
|
+
|| !isMissingProviderSessionError(error, recovery.isMissingProviderSession)
|
|
600
|
+
) throw error;
|
|
601
|
+
config.onRecoveryProgress?.({ stage: "load_failed" });
|
|
602
|
+
config.onRecoveryProgress?.({ stage: "loading_checkpoint" });
|
|
603
|
+
const checkpoint = await this.agent.persistence.recoveryCheckpoints?.latest(id);
|
|
604
|
+
if (!checkpoint) throw error;
|
|
605
|
+
config.onRecoveryProgress?.({ stage: "loading_checkpoint", checkpointId: checkpoint.checkpointId });
|
|
606
|
+
const seed = await buildRecoverySeed(
|
|
607
|
+
this.agent.persistence.messages,
|
|
608
|
+
id,
|
|
609
|
+
checkpoint,
|
|
610
|
+
summary.latestSequence,
|
|
611
|
+
recovery,
|
|
612
|
+
);
|
|
613
|
+
config.onRecoveryProgress?.({ stage: "creating_session", checkpointId: checkpoint.checkpointId });
|
|
614
|
+
const conversation = await this.start(id, summary.participants, {
|
|
615
|
+
...startConfig,
|
|
616
|
+
providerSession: "new",
|
|
617
|
+
deferProviderSessionPersistence: true,
|
|
618
|
+
});
|
|
619
|
+
try {
|
|
620
|
+
config.onRecoveryProgress?.({ stage: "seeding", checkpointId: checkpoint.checkpointId });
|
|
621
|
+
await conversation.seedRecoveryContext(seed.prompt);
|
|
622
|
+
await this.persistProviderSession(conversation, id, conversation.adapterId, {
|
|
623
|
+
transitionId: `recovery-${randomUUID()}`,
|
|
624
|
+
metadata: JSON.stringify({
|
|
625
|
+
recoveryCheckpointId: checkpoint.checkpointId,
|
|
626
|
+
previousInternalSessionId: active.internalSessionId,
|
|
627
|
+
recoveredThroughSequence: seed.recoveredThroughSequence,
|
|
628
|
+
}),
|
|
629
|
+
}, true);
|
|
630
|
+
} catch (recoveryError) {
|
|
631
|
+
this.live.delete(id);
|
|
632
|
+
await conversation.stop().catch(() => undefined);
|
|
633
|
+
throw recoveryError;
|
|
634
|
+
}
|
|
635
|
+
const result: ConversationRecoveryResult = Object.freeze({
|
|
636
|
+
checkpointId: checkpoint.checkpointId,
|
|
637
|
+
coveredSequence: checkpoint.coveredSequence,
|
|
638
|
+
recoveredThroughSequence: seed.recoveredThroughSequence,
|
|
639
|
+
previousInternalSessionId: active.internalSessionId,
|
|
640
|
+
newInternalSessionId: conversation.internalSessionId!,
|
|
641
|
+
});
|
|
642
|
+
config.onRecoveryProgress?.({ stage: "completed", checkpointId: checkpoint.checkpointId });
|
|
643
|
+
return Object.freeze({ conversation, providerSession: "recovered", recovery: result });
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
async get(id: AgentConversationId): Promise<AgentConversationSummary | null> {
|
|
648
|
+
return await this.agent.persistence.conversations.get(id);
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
async list(options?: ConversationListOptions): Promise<ConversationPage> {
|
|
652
|
+
return await this.agent.persistence.conversations.list(options);
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
async listPreviews(options?: ConversationListOptions): Promise<ConversationPreviewPage> {
|
|
656
|
+
if (!this.agent.persistence.conversations.listPreviews) {
|
|
657
|
+
throw new Error("conversation previews are unavailable on this persistence backend");
|
|
658
|
+
}
|
|
659
|
+
return await this.agent.persistence.conversations.listPreviews(options);
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
async delete(id: AgentConversationId, deletedAt?: string): Promise<void> {
|
|
663
|
+
const live = this.live.get(id);
|
|
664
|
+
if (live) await live.stop();
|
|
665
|
+
this.live.delete(id);
|
|
666
|
+
await this.agent.persistence.conversations.delete(id, deletedAt);
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
async stopAll(): Promise<void> {
|
|
670
|
+
await Promise.allSettled([...this.openings.values()]);
|
|
671
|
+
const conversations = [...this.live.values()];
|
|
672
|
+
this.live.clear();
|
|
673
|
+
await Promise.allSettled(conversations.map((conversation) => conversation.stop()));
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
async beginInternalInferenceMetering(
|
|
677
|
+
attempt: InternalInferenceSnapshot,
|
|
678
|
+
session: { readonly internalSessionId: string; readonly model: string | null },
|
|
679
|
+
): Promise<import("./internal-inference/contracts.ts").InternalInferenceMeteringOperation | null> {
|
|
680
|
+
const conversationId = attempt.agentConversationId;
|
|
681
|
+
const releaseSetup = conversationId
|
|
682
|
+
? await this.acquireMeteringSetupLock(conversationId)
|
|
683
|
+
: () => {};
|
|
684
|
+
let barrier: Promise<void> | undefined;
|
|
685
|
+
let releaseBarrier = () => {};
|
|
686
|
+
try {
|
|
687
|
+
const conversation = conversationId ? this.live.get(conversationId) : undefined;
|
|
688
|
+
if (conversation && conversation.state.phase !== "stopped") {
|
|
689
|
+
const operation = await conversation.beginDetachedMetering({
|
|
690
|
+
operationId: attempt.id,
|
|
691
|
+
operationKind: internalInferenceMeteringKind(attempt.purpose),
|
|
692
|
+
internalSessionId: session.internalSessionId,
|
|
693
|
+
model: session.model,
|
|
694
|
+
});
|
|
695
|
+
let closed = false;
|
|
696
|
+
releaseSetup();
|
|
697
|
+
return {
|
|
698
|
+
close: async ({ outcome, result, error }) => {
|
|
699
|
+
if (closed) throw new Error(`internal inference metering already closed: ${attempt.id}`);
|
|
700
|
+
closed = true;
|
|
701
|
+
return await conversation.closeDetachedMetering(operation, {
|
|
702
|
+
outcome,
|
|
703
|
+
usage: result?.usage ?? null,
|
|
704
|
+
...(error ? { usageFailureReason: String(error) } : {}),
|
|
705
|
+
});
|
|
706
|
+
},
|
|
707
|
+
settled() {},
|
|
708
|
+
};
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
const previous = conversationId
|
|
712
|
+
? this.detachedMeteringBarriers.get(conversationId) ?? Promise.resolve()
|
|
713
|
+
: this.agentMeteringBarrier ?? Promise.resolve();
|
|
714
|
+
const ownBarrier = new Promise<void>((resolve) => { releaseBarrier = resolve; });
|
|
715
|
+
barrier = previous.then(() => ownBarrier);
|
|
716
|
+
if (conversationId) this.detachedMeteringBarriers.set(conversationId, barrier);
|
|
717
|
+
else this.agentMeteringBarrier = barrier;
|
|
718
|
+
releaseSetup();
|
|
719
|
+
// Detached operations for one closed conversation must restore and commit in order.
|
|
720
|
+
// Otherwise two workers can derive the same next operation count from one snapshot.
|
|
721
|
+
await previous;
|
|
722
|
+
const persisted = conversationId
|
|
723
|
+
? await this.agent.persistence.metering.state(conversationId)
|
|
724
|
+
: await this.agent.persistence.metering.agentState(this.agent.id);
|
|
725
|
+
const meteringConfig = this.settings.defaults.metering;
|
|
726
|
+
const engine = new MeteringEngine({
|
|
727
|
+
agentSessionId: this.agent.id,
|
|
728
|
+
adapterId: attempt.adapterId,
|
|
729
|
+
enforcement: meteringConfig?.enforcement ?? "best_effort",
|
|
730
|
+
pricing: meteringConfig?.pricing ?? createModelsDevResolver(),
|
|
731
|
+
...(persisted ? { initialState: persisted.state } : {}),
|
|
732
|
+
createdActiveThread: false,
|
|
733
|
+
...(meteringConfig?.counterInterpretation
|
|
734
|
+
? { counterInterpretation: meteringConfig.counterInterpretation }
|
|
735
|
+
: {}),
|
|
736
|
+
...(meteringConfig?.inferenceSource
|
|
737
|
+
? { inferenceSource: meteringConfig.inferenceSource }
|
|
738
|
+
: {}),
|
|
739
|
+
});
|
|
740
|
+
const operation = await engine.openDetached({
|
|
741
|
+
operationId: attempt.id,
|
|
742
|
+
operationKind: internalInferenceMeteringKind(attempt.purpose),
|
|
743
|
+
internalSessionId: session.internalSessionId,
|
|
744
|
+
providerId: null,
|
|
745
|
+
model: session.model,
|
|
746
|
+
});
|
|
747
|
+
let closed = false;
|
|
748
|
+
let settled = false;
|
|
749
|
+
return {
|
|
750
|
+
close: async ({ outcome, result, error }) => {
|
|
751
|
+
if (closed) throw new Error(`internal inference metering already closed: ${attempt.id}`);
|
|
752
|
+
closed = true;
|
|
753
|
+
return await engine.closeDetached(operation, {
|
|
754
|
+
outcome,
|
|
755
|
+
reportedCumulative: result?.usage ?? null,
|
|
756
|
+
...(error ? { usageFailureReason: String(error) } : {}),
|
|
757
|
+
contextAfter: null,
|
|
758
|
+
providerCostAfter: null,
|
|
759
|
+
});
|
|
760
|
+
},
|
|
761
|
+
settled: () => {
|
|
762
|
+
if (settled) return;
|
|
763
|
+
settled = true;
|
|
764
|
+
if (conversationId && this.detachedMeteringBarriers.get(conversationId) === barrier) {
|
|
765
|
+
this.detachedMeteringBarriers.delete(conversationId);
|
|
766
|
+
} else if (!conversationId && this.agentMeteringBarrier === barrier) {
|
|
767
|
+
this.agentMeteringBarrier = undefined;
|
|
768
|
+
}
|
|
769
|
+
releaseBarrier();
|
|
770
|
+
},
|
|
771
|
+
};
|
|
772
|
+
} catch (error) {
|
|
773
|
+
releaseSetup();
|
|
774
|
+
if (barrier && conversationId && this.detachedMeteringBarriers.get(conversationId) === barrier) {
|
|
775
|
+
this.detachedMeteringBarriers.delete(conversationId);
|
|
776
|
+
} else if (barrier && !conversationId && this.agentMeteringBarrier === barrier) {
|
|
777
|
+
this.agentMeteringBarrier = undefined;
|
|
778
|
+
}
|
|
779
|
+
releaseBarrier();
|
|
780
|
+
throw error;
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
private async start(
|
|
785
|
+
id: AgentConversationId,
|
|
786
|
+
participants: readonly ParticipantRef[],
|
|
787
|
+
config: (CreateAgentConversationConfig | OpenAgentConversationConfig) & {
|
|
788
|
+
readonly providerSession: "new" | "load";
|
|
789
|
+
readonly internalSessionId?: string;
|
|
790
|
+
readonly deferProviderSessionPersistence?: boolean;
|
|
791
|
+
},
|
|
792
|
+
): Promise<AgentConversation> {
|
|
793
|
+
const releaseSetup = await this.acquireMeteringSetupLock(id);
|
|
794
|
+
let conversation: AgentConversation | undefined;
|
|
795
|
+
try {
|
|
796
|
+
const adapterId = this.resolveAdapterId(config.adapterId);
|
|
797
|
+
const adapter = this.agent.adapters.require(adapterId);
|
|
798
|
+
const runtime = { ...this.settings.defaults, ...config.runtime };
|
|
799
|
+
await this.detachedMeteringBarriers.get(id);
|
|
800
|
+
const persistedMetering = await this.agent.persistence.metering.state(id);
|
|
801
|
+
const lifecycle = new PersistedConversationLifecycle(
|
|
802
|
+
this.agent,
|
|
803
|
+
id,
|
|
804
|
+
participants,
|
|
805
|
+
this.settings,
|
|
806
|
+
);
|
|
807
|
+
conversation = await AgentConversation.create({
|
|
808
|
+
...runtime,
|
|
809
|
+
...(persistedMetering
|
|
810
|
+
? { metering: { ...runtime.metering, initialState: persistedMetering.state } }
|
|
811
|
+
: {}),
|
|
812
|
+
...("title" in config && config.title !== undefined ? { title: config.title } : {}),
|
|
813
|
+
adapter,
|
|
814
|
+
adapterId,
|
|
815
|
+
agentSessionId: this.agent.id,
|
|
816
|
+
ownerAgentSessionId: this.agent.id,
|
|
817
|
+
agentConversationId: id,
|
|
818
|
+
participants,
|
|
819
|
+
ownerLifecycle: lifecycle,
|
|
820
|
+
mode: config.mode ?? runtime.mode,
|
|
821
|
+
...(config.mcpServers ? { mcpServers: [...config.mcpServers] } : {}),
|
|
822
|
+
providerSession: config.providerSession === "load"
|
|
823
|
+
? { kind: "load", internalSessionId: config.internalSessionId!, onFailure: "error" }
|
|
824
|
+
: { kind: "new" },
|
|
825
|
+
persistence: false,
|
|
826
|
+
});
|
|
827
|
+
this.live.set(id, conversation);
|
|
828
|
+
conversation.subscribe((notification) => {
|
|
829
|
+
if (notification.event.kind === "state_changed" && notification.event.state.phase === "stopped") {
|
|
830
|
+
if (this.live.get(id) === conversation) this.live.delete(id);
|
|
831
|
+
}
|
|
832
|
+
});
|
|
833
|
+
if (conversation.internalSessionId && !config.deferProviderSessionPersistence) {
|
|
834
|
+
await this.persistProviderSession(conversation, id, adapterId, {}, config.providerSession === "new");
|
|
835
|
+
}
|
|
836
|
+
return conversation;
|
|
837
|
+
} catch (error) {
|
|
838
|
+
this.live.delete(id);
|
|
839
|
+
await conversation?.stop().catch(() => undefined);
|
|
840
|
+
throw error;
|
|
841
|
+
} finally {
|
|
842
|
+
releaseSetup();
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
private async acquireMeteringSetupLock(id: AgentConversationId): Promise<() => void> {
|
|
847
|
+
const previous = this.meteringSetupLocks.get(id) ?? Promise.resolve();
|
|
848
|
+
let releaseGate!: () => void;
|
|
849
|
+
const gate = new Promise<void>((resolve) => { releaseGate = resolve; });
|
|
850
|
+
const current = previous.then(() => gate);
|
|
851
|
+
this.meteringSetupLocks.set(id, current);
|
|
852
|
+
await previous;
|
|
853
|
+
let released = false;
|
|
854
|
+
return () => {
|
|
855
|
+
if (released) return;
|
|
856
|
+
released = true;
|
|
857
|
+
if (this.meteringSetupLocks.get(id) === current) this.meteringSetupLocks.delete(id);
|
|
858
|
+
releaseGate();
|
|
859
|
+
};
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
private resolveAdapterId(requested?: string): string {
|
|
863
|
+
if (requested) return requested;
|
|
864
|
+
if (this.settings.defaultAdapterId) return this.settings.defaultAdapterId;
|
|
865
|
+
const registrations = this.agent.adapters.list();
|
|
866
|
+
if (registrations.length === 1) return registrations[0]!.id;
|
|
867
|
+
throw new Error("adapterId is required when an Agent has no unique default adapter");
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
private async persistProviderSession(
|
|
871
|
+
conversation: AgentConversation,
|
|
872
|
+
id: AgentConversationId,
|
|
873
|
+
adapterId: string,
|
|
874
|
+
extra: { readonly transitionId?: string; readonly metadata?: string } = {},
|
|
875
|
+
newContext = false,
|
|
876
|
+
): Promise<void> {
|
|
877
|
+
if (!conversation.internalSessionId) throw new Error("provider session has no internal session id");
|
|
878
|
+
await this.agent.persistence.transaction(async (persistence) => {
|
|
879
|
+
if (newContext) await persistence.identityDelivery?.reset(id, conversation.internalSessionId!);
|
|
880
|
+
await persistence.providerSessions.append({
|
|
881
|
+
providerSessionRecordId: `provider-${randomUUID()}`,
|
|
882
|
+
agentConversationId: id,
|
|
883
|
+
internalSessionId: conversation.internalSessionId!,
|
|
884
|
+
adapterId,
|
|
885
|
+
mode: conversation.mode,
|
|
886
|
+
...(conversation.model ? { model: conversation.model } : {}),
|
|
887
|
+
activatedAt: new Date().toISOString(),
|
|
888
|
+
...extra,
|
|
889
|
+
});
|
|
890
|
+
});
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle {
|
|
895
|
+
constructor(
|
|
896
|
+
private readonly agent: Agent,
|
|
897
|
+
private readonly conversationId: AgentConversationId,
|
|
898
|
+
private readonly initialParticipants: readonly ParticipantRef[],
|
|
899
|
+
private readonly settings: ManagerSettings,
|
|
900
|
+
) {}
|
|
901
|
+
|
|
902
|
+
async beforePrompt(input: OwnedPromptInput) {
|
|
903
|
+
const participant = await this.resolveParticipant(input.participantId);
|
|
904
|
+
const identity = await this.agent.identity.load({
|
|
905
|
+
agentSessionId: this.agent.id,
|
|
906
|
+
agentConversationId: this.conversationId,
|
|
907
|
+
targetProviderContextId: input.targetProviderContextId,
|
|
908
|
+
participant,
|
|
909
|
+
prompt: input.text,
|
|
910
|
+
consistency: this.settings.identityConsistency,
|
|
911
|
+
...(this.settings.identityTimeoutMs !== undefined
|
|
912
|
+
? { timeoutMs: this.settings.identityTimeoutMs }
|
|
913
|
+
: {}),
|
|
914
|
+
});
|
|
915
|
+
const records = await this.appendMessages([{
|
|
916
|
+
recordId: `${input.operationId}:user`,
|
|
917
|
+
agentSessionId: this.agent.id,
|
|
918
|
+
agentConversationId: this.conversationId,
|
|
919
|
+
kind: "message",
|
|
920
|
+
timestamp: new Date().toISOString(),
|
|
921
|
+
role: "user",
|
|
922
|
+
participantId: participant.id,
|
|
923
|
+
...(input.consumerMetadata !== undefined ? { consumerMetadata: input.consumerMetadata } : {}),
|
|
924
|
+
content: input.text,
|
|
925
|
+
status: "completed",
|
|
926
|
+
metadata: JSON.stringify({ operationId: input.operationId }),
|
|
927
|
+
}]);
|
|
928
|
+
await this.updateIdentity(records);
|
|
929
|
+
return Object.freeze({
|
|
930
|
+
providerText: composeIdentityPrompt(input.text, identity),
|
|
931
|
+
participant,
|
|
932
|
+
...(identity.deliveryReceipt ? { identityDeliveryReceipt: identity.deliveryReceipt } : {}),
|
|
933
|
+
});
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
async afterPrompt(input: OwnedPromptCompleted): Promise<void> {
|
|
937
|
+
const timestamp = new Date().toISOString();
|
|
938
|
+
const status = input.result.status === "error" ? "failed" : input.result.status;
|
|
939
|
+
const records = input.result.messages.map((message, index): NewConversationRecord => ({
|
|
940
|
+
recordId: `${input.operationId}:assistant:${index + 1}`,
|
|
941
|
+
agentSessionId: this.agent.id,
|
|
942
|
+
agentConversationId: this.conversationId,
|
|
943
|
+
kind: "message",
|
|
944
|
+
timestamp,
|
|
945
|
+
role: "assistant",
|
|
946
|
+
content: message.text,
|
|
947
|
+
status,
|
|
948
|
+
metadata: JSON.stringify({
|
|
949
|
+
operationId: input.operationId,
|
|
950
|
+
...(message.messageId ? { providerMessageId: message.messageId } : {}),
|
|
951
|
+
}),
|
|
952
|
+
}));
|
|
953
|
+
await this.updateIdentity(await this.appendMessages(records));
|
|
954
|
+
if (status === "completed" && input.identityDeliveryReceipt) {
|
|
955
|
+
await this.agent.identity.delivered?.(input.identityDeliveryReceipt);
|
|
956
|
+
}
|
|
957
|
+
if (status === "completed") {
|
|
958
|
+
await this.agent.checkpointing?.afterSuccessfulResponse(this.conversationId);
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
async promptFailed(input: OwnedPromptFailed): Promise<void> {
|
|
963
|
+
const timestamp = new Date().toISOString();
|
|
964
|
+
const records = input.messages.map((message, index): NewConversationRecord => ({
|
|
965
|
+
recordId: `${input.operationId}:assistant:${index + 1}`,
|
|
966
|
+
agentSessionId: this.agent.id,
|
|
967
|
+
agentConversationId: this.conversationId,
|
|
968
|
+
kind: "message",
|
|
969
|
+
timestamp,
|
|
970
|
+
role: "assistant",
|
|
971
|
+
content: message.text,
|
|
972
|
+
status: "failed",
|
|
973
|
+
metadata: JSON.stringify({
|
|
974
|
+
operationId: input.operationId,
|
|
975
|
+
...(message.messageId ? { providerMessageId: message.messageId } : {}),
|
|
976
|
+
}),
|
|
977
|
+
}));
|
|
978
|
+
await this.updateIdentity(await this.appendMessages(records));
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
resolveAdapter(adapterId: string) {
|
|
982
|
+
return this.agent.adapters.require(adapterId);
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
async transitionActivated(input: {
|
|
986
|
+
readonly transitionId: string;
|
|
987
|
+
readonly agentConversationId: AgentConversationId;
|
|
988
|
+
readonly internalSessionId: string;
|
|
989
|
+
readonly adapterId: string;
|
|
990
|
+
readonly mode: AgentMode;
|
|
991
|
+
readonly model?: string;
|
|
992
|
+
readonly activatedAt: string;
|
|
993
|
+
}): Promise<void> {
|
|
994
|
+
await this.agent.persistence.transaction(async (persistence) => {
|
|
995
|
+
await persistence.identityDelivery?.reset(input.agentConversationId, input.internalSessionId);
|
|
996
|
+
await persistence.providerSessions.append({
|
|
997
|
+
providerSessionRecordId: `provider-${randomUUID()}`,
|
|
998
|
+
agentConversationId: input.agentConversationId,
|
|
999
|
+
internalSessionId: input.internalSessionId,
|
|
1000
|
+
adapterId: input.adapterId,
|
|
1001
|
+
mode: input.mode,
|
|
1002
|
+
...(input.model ? { model: input.model } : {}),
|
|
1003
|
+
activatedAt: input.activatedAt,
|
|
1004
|
+
transitionId: input.transitionId,
|
|
1005
|
+
});
|
|
1006
|
+
});
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
async record(record: NewConversationRecord): Promise<void> {
|
|
1010
|
+
await this.updateIdentity(await this.persistObservations([record]));
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
async meteringRecorded(record: OperationMeteringRecord): Promise<void> {
|
|
1014
|
+
const level = this.settings.capture.metering;
|
|
1015
|
+
let reference: ConversationRecord | undefined;
|
|
1016
|
+
await this.agent.persistence.transaction(async (persistence) => {
|
|
1017
|
+
await persistence.metering.commit({
|
|
1018
|
+
agentConversationId: this.conversationId,
|
|
1019
|
+
record,
|
|
1020
|
+
meteringRecords: this.settings.meteringRecords,
|
|
1021
|
+
});
|
|
1022
|
+
const timelineRecord: NewConversationRecord = {
|
|
1023
|
+
recordId: `${record.operationId}:metering`,
|
|
1024
|
+
agentSessionId: this.agent.id,
|
|
1025
|
+
agentConversationId: this.conversationId,
|
|
1026
|
+
kind: "metering",
|
|
1027
|
+
timestamp: new Date(record.completedAt).toISOString(),
|
|
1028
|
+
operationId: record.operationId,
|
|
1029
|
+
meteringRecordId: record.operationId,
|
|
1030
|
+
status: record.usage.status === "metered" ? "available" : "unavailable",
|
|
1031
|
+
metadata: JSON.stringify({ operationId: record.operationId }),
|
|
1032
|
+
};
|
|
1033
|
+
if (level !== "none") {
|
|
1034
|
+
reference = await persistence.records.append(captureRuntimeRecord(timelineRecord, level));
|
|
1035
|
+
}
|
|
1036
|
+
if (this.settings.auditLog) {
|
|
1037
|
+
await enqueueAuditObservation(persistence, {
|
|
1038
|
+
scope: "conversation",
|
|
1039
|
+
sourceObservationId: timelineRecord.recordId,
|
|
1040
|
+
operationId: record.operationId,
|
|
1041
|
+
record: timelineRecord,
|
|
1042
|
+
meteringRecord: record,
|
|
1043
|
+
}, this.settings.auditLog);
|
|
1044
|
+
}
|
|
1045
|
+
});
|
|
1046
|
+
if (this.settings.auditLog) this.agent.audit?.notifyPending();
|
|
1047
|
+
if (reference) await this.updateIdentity([reference]);
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
async meteringStateChanged(state: AgentSessionMeteringState): Promise<void> {
|
|
1051
|
+
await this.agent.persistence.metering.saveState(this.conversationId, state);
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
private async resolveParticipant(participantId?: string): Promise<ParticipantRef> {
|
|
1055
|
+
const id = participantId
|
|
1056
|
+
?? (this.initialParticipants.length === 1
|
|
1057
|
+
? this.initialParticipants[0]!.id
|
|
1058
|
+
: IMPLICIT_USER_PARTICIPANT_ID);
|
|
1059
|
+
const existing = (await this.agent.persistence.conversations.get(this.conversationId))
|
|
1060
|
+
?.participants.find((participant) => participant.id === id);
|
|
1061
|
+
if (existing) return existing;
|
|
1062
|
+
return await this.agent.persistence.conversations.ensureParticipant(this.conversationId, {
|
|
1063
|
+
id,
|
|
1064
|
+
kind: "user",
|
|
1065
|
+
});
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
private async appendMessages(
|
|
1069
|
+
records: readonly NewConversationRecord[],
|
|
1070
|
+
): Promise<readonly ConversationRecord[]> {
|
|
1071
|
+
return await this.persistObservations(records);
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
private async persistObservations(
|
|
1075
|
+
records: readonly NewConversationRecord[],
|
|
1076
|
+
): Promise<readonly ConversationRecord[]> {
|
|
1077
|
+
if (records.length === 0) return Object.freeze([]);
|
|
1078
|
+
if (!this.settings.auditLog && records.every((record) => {
|
|
1079
|
+
if (record.kind !== "protocol") return this.settings.capture[record.kind] === "none";
|
|
1080
|
+
return this.settings.capture.protocol.level === "none"
|
|
1081
|
+
|| !shouldCaptureProtocolMethod(this.settings.capture.protocol, record.method);
|
|
1082
|
+
})) return Object.freeze([]);
|
|
1083
|
+
const persisted: ConversationRecord[] = [];
|
|
1084
|
+
await this.agent.persistence.transaction(async (persistence) => {
|
|
1085
|
+
for (const record of records) {
|
|
1086
|
+
const level = record.kind === "protocol"
|
|
1087
|
+
? this.settings.capture.protocol.level
|
|
1088
|
+
: this.settings.capture[record.kind];
|
|
1089
|
+
const canonicalAccepted = level !== "none" && (
|
|
1090
|
+
record.kind !== "protocol"
|
|
1091
|
+
|| shouldCaptureProtocolMethod(this.settings.capture.protocol, record.method)
|
|
1092
|
+
);
|
|
1093
|
+
if (canonicalAccepted) {
|
|
1094
|
+
persisted.push(await persistence.records.append(captureRuntimeRecord(record, level)));
|
|
1095
|
+
}
|
|
1096
|
+
if (this.settings.auditLog) {
|
|
1097
|
+
await enqueueAuditObservation(persistence, {
|
|
1098
|
+
scope: "conversation",
|
|
1099
|
+
sourceObservationId: record.recordId,
|
|
1100
|
+
operationId: operationIdFromMetadata(record.metadata),
|
|
1101
|
+
record,
|
|
1102
|
+
}, this.settings.auditLog);
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
});
|
|
1106
|
+
if (this.settings.auditLog) this.agent.audit?.notifyPending();
|
|
1107
|
+
return Object.freeze(persisted);
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
private async updateIdentity(records: readonly ConversationRecord[]): Promise<void> {
|
|
1111
|
+
await this.agent.identity.update({
|
|
1112
|
+
agentSessionId: this.agent.id,
|
|
1113
|
+
agentConversationId: this.conversationId,
|
|
1114
|
+
records,
|
|
1115
|
+
});
|
|
1116
|
+
await this.settings.auditIdentityUpdate(this.conversationId, records);
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
function normalizeParticipants(participants?: readonly ParticipantRef[]): readonly ParticipantRef[] {
|
|
1121
|
+
const values = participants?.length
|
|
1122
|
+
? participants.map(normalizeParticipantRef)
|
|
1123
|
+
: [{ id: IMPLICIT_USER_PARTICIPANT_ID, kind: "user" as const }];
|
|
1124
|
+
const seen = new Set<string>();
|
|
1125
|
+
for (const participant of values) {
|
|
1126
|
+
if (seen.has(participant.id)) throw new Error(`duplicate participant id: ${participant.id}`);
|
|
1127
|
+
seen.add(participant.id);
|
|
1128
|
+
}
|
|
1129
|
+
return Object.freeze(values);
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
function internalInferenceMeteringKind(purpose: string): MeteredOperationKind {
|
|
1133
|
+
if (
|
|
1134
|
+
purpose === "conversation_checkpoint"
|
|
1135
|
+
|| purpose === "conversation_recovery"
|
|
1136
|
+
|| purpose === "identity_update"
|
|
1137
|
+
) return purpose;
|
|
1138
|
+
return "internal_command";
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
function captureRuntimeRecord(
|
|
1142
|
+
record: NewConversationRecord,
|
|
1143
|
+
level: RecordCaptureLevel,
|
|
1144
|
+
): NewConversationRecord {
|
|
1145
|
+
if (level !== "metadata") return record;
|
|
1146
|
+
switch (record.kind) {
|
|
1147
|
+
case "message":
|
|
1148
|
+
return { ...record, content: "" };
|
|
1149
|
+
case "tool_call":
|
|
1150
|
+
return {
|
|
1151
|
+
recordId: record.recordId,
|
|
1152
|
+
agentSessionId: record.agentSessionId,
|
|
1153
|
+
agentConversationId: record.agentConversationId,
|
|
1154
|
+
kind: record.kind,
|
|
1155
|
+
timestamp: record.timestamp,
|
|
1156
|
+
...(record.metadata ? { metadata: record.metadata } : {}),
|
|
1157
|
+
toolCallId: record.toolCallId,
|
|
1158
|
+
state: record.state,
|
|
1159
|
+
...(record.name ? { name: record.name } : {}),
|
|
1160
|
+
};
|
|
1161
|
+
case "permission":
|
|
1162
|
+
return {
|
|
1163
|
+
recordId: record.recordId,
|
|
1164
|
+
agentSessionId: record.agentSessionId,
|
|
1165
|
+
agentConversationId: record.agentConversationId,
|
|
1166
|
+
kind: record.kind,
|
|
1167
|
+
timestamp: record.timestamp,
|
|
1168
|
+
...(record.metadata ? { metadata: record.metadata } : {}),
|
|
1169
|
+
permissionId: record.permissionId,
|
|
1170
|
+
state: record.state,
|
|
1171
|
+
...(record.outcome ? { outcome: record.outcome } : {}),
|
|
1172
|
+
};
|
|
1173
|
+
case "configuration":
|
|
1174
|
+
return { ...record, value: undefined };
|
|
1175
|
+
case "protocol":
|
|
1176
|
+
return { ...record, message: undefined };
|
|
1177
|
+
case "native_action":
|
|
1178
|
+
case "agent_action":
|
|
1179
|
+
return { ...record, input: undefined, output: undefined };
|
|
1180
|
+
case "thinking":
|
|
1181
|
+
return { ...record, content: "" };
|
|
1182
|
+
case "activity":
|
|
1183
|
+
return { ...record, content: undefined, data: undefined };
|
|
1184
|
+
case "metering":
|
|
1185
|
+
return record;
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
async function enqueueAuditObservation(
|
|
1190
|
+
persistence: PersistenceBackend | PersistenceScope,
|
|
1191
|
+
observation: NormalizedAgentObservation,
|
|
1192
|
+
config: ResolvedAgentAuditLogConfig,
|
|
1193
|
+
): Promise<void> {
|
|
1194
|
+
const projected = projectAgentAuditObservation(observation, config.capture);
|
|
1195
|
+
if (!projected) return;
|
|
1196
|
+
if (!persistence.auditOutbox) throw new PersistenceCapabilityError("auditOutbox");
|
|
1197
|
+
await persistence.auditOutbox.enqueue({
|
|
1198
|
+
outboxId: `aud-${randomUUID()}`,
|
|
1199
|
+
sourceObservationId: projected.sourceObservationId,
|
|
1200
|
+
...(projected.sourceRecordId ? { sourceRecordId: projected.sourceRecordId } : {}),
|
|
1201
|
+
...(projected.operationId ? { operationId: projected.operationId } : {}),
|
|
1202
|
+
...(projected.agentConversationId ? { agentConversationId: projected.agentConversationId } : {}),
|
|
1203
|
+
occurredAt: projected.occurredAt,
|
|
1204
|
+
kind: projected.kind,
|
|
1205
|
+
captureLevel: projected.captureLevel,
|
|
1206
|
+
captureFingerprint: config.captureFingerprint,
|
|
1207
|
+
payload: projected.payload,
|
|
1208
|
+
createdAt: new Date().toISOString(),
|
|
1209
|
+
});
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
function operationIdFromMetadata(metadata: string | undefined): string | undefined {
|
|
1213
|
+
if (!metadata) return undefined;
|
|
1214
|
+
try {
|
|
1215
|
+
const value = JSON.parse(metadata) as { operationId?: unknown };
|
|
1216
|
+
return typeof value.operationId === "string" && value.operationId ? value.operationId : undefined;
|
|
1217
|
+
} catch {
|
|
1218
|
+
return undefined;
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
export { AgentAdapterRegistry, NoopAgentIdentityRuntime, composeIdentityPrompt };
|
|
1223
|
+
export type { AgentAdapterRegistration, AgentIdentityRuntime, IdentityConsistency };
|