@qlairoslabs/acp-client 0.11.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG-consumer-fixes.md +55 -0
- package/CHANGELOG-operation-lifecycle.md +64 -0
- package/CONSUMER_GUIDE.md +311 -17
- package/MIGRATION-0.10-to-0.12.md +189 -0
- package/README.md +6 -3
- package/package.json +5 -2
- package/src/adapters.ts +3 -1
- package/src/agent/adoption/checkpoint-floor.ts +47 -0
- package/src/agent/adoption/index.ts +3 -1
- package/src/agent/adoption/replay.ts +15 -0
- package/src/agent/config.ts +4 -0
- package/src/agent/conversation-manager.ts +223 -153
- package/src/agent/error-record-writer.ts +77 -0
- package/src/agent/persisted-lifecycle.ts +152 -35
- package/src/agent/record-capture.ts +18 -18
- package/src/agent-adapter-registry.ts +2 -0
- package/src/agent-client.ts +9 -3
- package/src/agent-conversation-contracts.ts +6 -0
- package/src/agent-conversation-owner.ts +31 -6
- package/src/agent-conversation-presentation.ts +12 -1
- package/src/agent-conversation-queue.ts +3 -2
- package/src/agent-session.ts +537 -96
- package/src/agent.ts +46 -23
- package/src/audit/config.ts +4 -0
- package/src/audit/projection.ts +3 -0
- package/src/checkpointing/contracts.ts +28 -3
- package/src/checkpointing/persistence/sqlite-repository.ts +36 -8
- package/src/checkpointing/recovery.ts +9 -2
- package/src/checkpointing/strategy.ts +27 -2
- package/src/client.ts +120 -30
- package/src/controller.ts +116 -7
- package/src/degraded/pty-client.ts +25 -1
- package/src/identity/checkpoint-backed.ts +2 -2
- package/src/index.ts +17 -0
- package/src/internal-inference/config.ts +7 -0
- package/src/internal-inference/contracts.ts +3 -0
- package/src/internal-inference/coordination/handles.ts +11 -2
- package/src/internal-inference/coordination/manager.ts +20 -3
- package/src/internal-inference/index.ts +2 -0
- package/src/internal-inference/persistence/records.ts +3 -1
- package/src/internal-inference/persistence/sqlite-repository.ts +4 -1
- package/src/internal-inference/runtime/disposable-session-env.ts +84 -0
- package/src/internal-inference/runtime/harness-runtime.ts +19 -2
- package/src/media/acp.ts +118 -0
- package/src/media/capture.ts +15 -0
- package/src/media/content.ts +142 -0
- package/src/media/files.ts +28 -0
- package/src/media/parts.ts +145 -0
- package/src/media/pending.ts +51 -0
- package/src/media/redact.ts +14 -0
- package/src/media/store.ts +127 -0
- package/src/metering/provider.ts +8 -1
- package/src/operations/activity-tracker.ts +31 -0
- package/src/operations/contracts.ts +63 -0
- package/src/operations/errors.ts +31 -0
- package/src/operations/index.ts +6 -0
- package/src/operations/stale-policy.ts +51 -0
- package/src/operations/supervisor.ts +209 -0
- package/src/operations/timers.ts +12 -0
- package/src/out-of-band-messages.ts +49 -32
- package/src/persistence/audit-runtime.ts +14 -2
- package/src/persistence/backend.ts +108 -12
- package/src/persistence/error-records.ts +27 -0
- package/src/persistence/index.ts +8 -0
- package/src/persistence/presentation.ts +9 -1
- package/src/persistence/projection.ts +20 -0
- package/src/persistence/records.ts +45 -6
- package/src/persistence/sqlite-backend.ts +207 -16
- package/src/persistence/sqlite-conversation-records.ts +31 -4
- package/src/persistence/sqlite-files.ts +95 -0
- package/src/persistence/sqlite-media-store.ts +67 -0
- package/src/persistence/sqlite-schema.ts +146 -13
- package/src/persistence/state-runtime.ts +2 -0
- package/src/persistence/timeline-reconcile.ts +21 -4
- package/src/persistence/transcript-reader.ts +11 -4
- package/src/persistence/transcript-runtime.ts +105 -12
- package/src/repl/repl.ts +1 -1
- package/src/response.ts +40 -8
- package/src/steering/combine.ts +11 -4
- package/src/steering/contracts.ts +14 -4
- package/src/steering/controller.ts +96 -21
- package/src/steering/index.ts +1 -0
- package/src/transport/acp-transport.ts +18 -7
- package/src/types.ts +7 -0
- package/src/updates.ts +4 -4
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { writeConversationError } from "./error-record-writer.ts";
|
|
1
2
|
import { randomUUID } from "node:crypto";
|
|
2
3
|
import {
|
|
3
4
|
createAgentConversationId,
|
|
@@ -41,6 +42,7 @@ import type { ManagerSettings } from "./manager-settings.ts";
|
|
|
41
42
|
import {
|
|
42
43
|
updateConversationIdentity,
|
|
43
44
|
persistConversationObservations,
|
|
45
|
+
persistObservationsInTransaction,
|
|
44
46
|
normalizeParticipants,
|
|
45
47
|
internalInferenceMeteringKind,
|
|
46
48
|
appendCanonicalRecord,
|
|
@@ -74,12 +76,20 @@ import {
|
|
|
74
76
|
normalizeAdoption,
|
|
75
77
|
selectTail,
|
|
76
78
|
turnsFromReplay,
|
|
79
|
+
withoutRecapTurns,
|
|
80
|
+
publishAdoptionFloor,
|
|
81
|
+
DEFAULT_ADOPTION_TAIL_MESSAGES,
|
|
82
|
+
type AdoptionRecapPlacement,
|
|
77
83
|
type ListProviderSessionsOptions,
|
|
78
84
|
type NormalizedAdoption,
|
|
79
85
|
type ProviderSessionSummary,
|
|
80
86
|
} from "./adoption/index.ts";
|
|
81
87
|
import { NoopAgentIdentityRuntime } from "../identity.ts";
|
|
82
88
|
import type { ConversationPersistenceContext } from "./persistence-policy/index.ts";
|
|
89
|
+
import { forgetPendingParts, pendingOutOfBandParts } from "../media/pending.ts";
|
|
90
|
+
import { resolveParts } from "../media/store.ts";
|
|
91
|
+
import { persistParts } from "../media/content.ts";
|
|
92
|
+
import { isMediaPart, promptParts, partsText } from "../media/parts.ts";
|
|
83
93
|
|
|
84
94
|
export class DefaultAgentConversationManager implements AgentConversationManager {
|
|
85
95
|
private readonly live = new Map<AgentConversationId, AgentConversation>();
|
|
@@ -226,11 +236,12 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
226
236
|
}
|
|
227
237
|
try {
|
|
228
238
|
await this.recordAdoptedProviderSession(conversation, id, attemptId);
|
|
229
|
-
|
|
239
|
+
const recap = adoption.recap ? await this.recap(conversation, id, attemptId, settings) : undefined;
|
|
230
240
|
if (adoption.importHistory) {
|
|
231
|
-
const turns = selectTail(turnsFromReplay(replay), adoption.importHistory.last);
|
|
241
|
+
const turns = selectTail(withoutRecapTurns(turnsFromReplay(replay)), adoption.importHistory.last);
|
|
232
242
|
await conversation.importHistory(turns, `${attemptId}-import`);
|
|
233
243
|
}
|
|
244
|
+
await this.placeCheckpointFloor(id, recap, settings);
|
|
234
245
|
} catch (error) {
|
|
235
246
|
this.live.delete(id);
|
|
236
247
|
await conversation.stop().catch(() => undefined);
|
|
@@ -249,11 +260,16 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
249
260
|
id: AgentConversationId,
|
|
250
261
|
attemptId: string,
|
|
251
262
|
settings: ManagerSettings,
|
|
252
|
-
): Promise<
|
|
263
|
+
): Promise<AdoptionRecapPlacement | undefined> {
|
|
253
264
|
const recapId = `${attemptId}-recap`;
|
|
254
265
|
try {
|
|
255
266
|
const summary = await conversation.requestRecap(RECAP_INSTRUCTION, recapId);
|
|
256
267
|
await conversation.recordRecap(summary, recapId, RECAP_ORIGIN);
|
|
268
|
+
// Stored before anything is imported, so its sequence is the last one so far. A conversation that
|
|
269
|
+
// stores no messages has no sequence to cover (adoption requires `content` capture, so this is a
|
|
270
|
+
// backend without checkpoints).
|
|
271
|
+
const sequence = await this.agent.persistence.recoveryCheckpoints?.latestMessageSequence(id);
|
|
272
|
+
return sequence ? { summary: summary.trim(), sequence } : undefined;
|
|
257
273
|
} catch (error) {
|
|
258
274
|
await this.recordConversationError({
|
|
259
275
|
settings,
|
|
@@ -265,6 +281,38 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
265
281
|
message: "The adopted session could not be summarized.",
|
|
266
282
|
details: providerSessionErrorDetails(error),
|
|
267
283
|
});
|
|
284
|
+
return undefined;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Put the conversation's checkpoint floor after the adopted history (see `publishAdoptionFloor`), when the
|
|
290
|
+
* conversation checkpoints at all. A failure here is recorded and does not fail the adoption: the
|
|
291
|
+
* conversation is usable, and its first scheduled checkpoint then starts from whatever is stored.
|
|
292
|
+
*/
|
|
293
|
+
private async placeCheckpointFloor(
|
|
294
|
+
id: AgentConversationId,
|
|
295
|
+
recap: AdoptionRecapPlacement | undefined,
|
|
296
|
+
settings: ManagerSettings,
|
|
297
|
+
): Promise<void> {
|
|
298
|
+
const repository = this.agent.persistence.recoveryCheckpoints;
|
|
299
|
+
if (!repository || !settings.checkpointing?.enabled) return;
|
|
300
|
+
try {
|
|
301
|
+
await publishAdoptionFloor(repository, id, {
|
|
302
|
+
...(recap ? { recap } : {}),
|
|
303
|
+
tailMessages: Math.min(DEFAULT_ADOPTION_TAIL_MESSAGES, settings.checkpointing.recovery.maxTailMessages),
|
|
304
|
+
});
|
|
305
|
+
} catch (error) {
|
|
306
|
+
await this.recordConversationError({
|
|
307
|
+
settings,
|
|
308
|
+
agentConversationId: id,
|
|
309
|
+
attemptId: `${id}-checkpoint-floor`,
|
|
310
|
+
source: "operation",
|
|
311
|
+
code: "adoption_checkpoint_floor_failed",
|
|
312
|
+
recoverability: "retryable",
|
|
313
|
+
message: "The checkpoint floor of the adopted conversation could not be placed.",
|
|
314
|
+
details: providerSessionErrorDetails(error),
|
|
315
|
+
});
|
|
268
316
|
}
|
|
269
317
|
}
|
|
270
318
|
|
|
@@ -410,107 +458,119 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
410
458
|
} catch (error) {
|
|
411
459
|
// No recorded mapping means this open was creating a thread, not loading one.
|
|
412
460
|
if (!active) return await this.throwCreateFailure(id, attemptId, error, settings);
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
461
|
+
return await this.recoverAfterLoadFailure(id, active.internalSessionId, error, settings, config,
|
|
462
|
+
async () => await this.start(id, summary.participants, { ...startConfig, providerSession: "new", settings }),
|
|
463
|
+
async (conversation) => {
|
|
464
|
+
this.live.delete(id);
|
|
465
|
+
await conversation.stop().catch(() => undefined);
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/** Shared recovery policy for opening and reconnecting the same logical conversation. */
|
|
471
|
+
private async recoverAfterLoadFailure(
|
|
472
|
+
id: AgentConversationId, previousInternalSessionId: string, error: unknown, settings: ManagerSettings,
|
|
473
|
+
config: Pick<OpenAgentConversationConfig, "onRecoveryProgress">,
|
|
474
|
+
fresh: () => Promise<AgentConversation>, dispose: (conversation: AgentConversation) => Promise<void>,
|
|
475
|
+
): Promise<OpenOwnedAgentConversationResult> {
|
|
476
|
+
const summary = await this.agent.persistence.conversations.get(id);
|
|
477
|
+
if (!summary) throw new Error(`unknown conversation: ${id}`);
|
|
478
|
+
const attemptId = `provider-load-${randomUUID()}`;
|
|
479
|
+
const recovery = settings.checkpointing?.recovery;
|
|
480
|
+
const classification = classifyProviderSessionLoadError(error, recovery?.isMissingProviderSession);
|
|
481
|
+
const recorded = await this.recordConversationError({
|
|
482
|
+
settings,
|
|
483
|
+
agentConversationId: id,
|
|
484
|
+
attemptId,
|
|
485
|
+
source: "provider_session",
|
|
486
|
+
code: classification.code,
|
|
487
|
+
recoverability: classification.recoverability,
|
|
488
|
+
message: "The provider session could not be loaded.",
|
|
489
|
+
transitionId: attemptId,
|
|
490
|
+
internalSessionId: previousInternalSessionId,
|
|
491
|
+
details: providerSessionErrorDetails(error),
|
|
492
|
+
});
|
|
493
|
+
const structuredError = (): ProviderSessionError => new ProviderSessionError({
|
|
494
|
+
agentSessionId: this.agent.id,
|
|
495
|
+
agentConversationId: id,
|
|
496
|
+
attemptId,
|
|
497
|
+
internalSessionId: previousInternalSessionId,
|
|
498
|
+
code: classification.code,
|
|
499
|
+
source: "provider_session",
|
|
500
|
+
recoverability: classification.recoverability,
|
|
501
|
+
...(recorded.record ? { recordId: recorded.record.recordId } : {}),
|
|
502
|
+
...(recorded.recordingError ? { recordingError: recorded.recordingError } : {}),
|
|
503
|
+
cause: error,
|
|
504
|
+
});
|
|
505
|
+
if (recovery?.onLoadFailure !== "recover" || !classification.missing) throw structuredError();
|
|
506
|
+
config.onRecoveryProgress?.({ stage: "load_failed" });
|
|
507
|
+
config.onRecoveryProgress?.({ stage: "loading_checkpoint" });
|
|
508
|
+
const checkpoint = await this.agent.persistence.recoveryCheckpoints?.latest(id);
|
|
509
|
+
if (!checkpoint) throw structuredError();
|
|
510
|
+
config.onRecoveryProgress?.({ stage: "loading_checkpoint", checkpointId: checkpoint.checkpointId });
|
|
511
|
+
const recoveryAttemptId = `recovery-${randomUUID()}`;
|
|
512
|
+
try {
|
|
513
|
+
const seed = await buildRecoverySeed(
|
|
514
|
+
this.agent.persistence.messages,
|
|
515
|
+
id,
|
|
516
|
+
checkpoint,
|
|
517
|
+
summary.latestSequence,
|
|
518
|
+
recovery,
|
|
519
|
+
);
|
|
520
|
+
config.onRecoveryProgress?.({ stage: "creating_session", checkpointId: checkpoint.checkpointId });
|
|
521
|
+
const conversation = await fresh();
|
|
522
|
+
try {
|
|
523
|
+
config.onRecoveryProgress?.({ stage: "seeding", checkpointId: checkpoint.checkpointId });
|
|
524
|
+
await conversation.seedRecoveryContext(seed.prompt);
|
|
525
|
+
const acknowledgement = await this.persistProviderSession(conversation, id, {
|
|
526
|
+
transitionId: recoveryAttemptId,
|
|
527
|
+
metadata: JSON.stringify({
|
|
528
|
+
recoveryCheckpointId: checkpoint.checkpointId,
|
|
529
|
+
previousInternalSessionId,
|
|
530
|
+
recoveredThroughSequence: seed.recoveredThroughSequence,
|
|
531
|
+
}),
|
|
532
|
+
}, true);
|
|
533
|
+
conversation.acknowledgeProviderAttachment(acknowledgement);
|
|
534
|
+
} catch (recoveryError) {
|
|
535
|
+
await dispose(conversation);
|
|
536
|
+
throw recoveryError;
|
|
537
|
+
}
|
|
538
|
+
const result: ConversationRecoveryResult = Object.freeze({
|
|
539
|
+
checkpointId: checkpoint.checkpointId,
|
|
540
|
+
coveredSequence: checkpoint.coveredSequence,
|
|
541
|
+
recoveredThroughSequence: seed.recoveredThroughSequence,
|
|
542
|
+
previousInternalSessionId,
|
|
543
|
+
newInternalSessionId: conversation.internalSessionId!,
|
|
544
|
+
});
|
|
545
|
+
config.onRecoveryProgress?.({ stage: "completed", checkpointId: checkpoint.checkpointId });
|
|
546
|
+
return Object.freeze({ conversation, providerSession: "recovered", recovery: result });
|
|
547
|
+
} catch (recoveryError) {
|
|
548
|
+
// A recovery failure is a distinct root cause from the load failure already
|
|
549
|
+
// recorded above; it prevents the logical conversation from reopening.
|
|
550
|
+
const recoveryRecorded = await this.recordConversationError({
|
|
416
551
|
settings,
|
|
417
552
|
agentConversationId: id,
|
|
418
|
-
attemptId,
|
|
419
|
-
source: "
|
|
420
|
-
code:
|
|
421
|
-
recoverability:
|
|
422
|
-
message: "The
|
|
423
|
-
transitionId:
|
|
424
|
-
internalSessionId:
|
|
425
|
-
details: providerSessionErrorDetails(error),
|
|
553
|
+
attemptId: recoveryAttemptId,
|
|
554
|
+
source: "recovery",
|
|
555
|
+
code: "recovery_failed",
|
|
556
|
+
recoverability: "recoverable",
|
|
557
|
+
message: "The conversation could not be recovered from its checkpoint.",
|
|
558
|
+
transitionId: recoveryAttemptId,
|
|
559
|
+
internalSessionId: previousInternalSessionId,
|
|
426
560
|
});
|
|
427
|
-
|
|
561
|
+
throw new ProviderSessionError({
|
|
428
562
|
agentSessionId: this.agent.id,
|
|
429
563
|
agentConversationId: id,
|
|
430
|
-
attemptId,
|
|
431
|
-
internalSessionId:
|
|
432
|
-
code:
|
|
433
|
-
source: "
|
|
434
|
-
recoverability:
|
|
435
|
-
|
|
436
|
-
...(
|
|
437
|
-
|
|
564
|
+
attemptId: recoveryAttemptId,
|
|
565
|
+
internalSessionId: previousInternalSessionId,
|
|
566
|
+
code: "recovery_failed",
|
|
567
|
+
source: "recovery",
|
|
568
|
+
recoverability: "recoverable",
|
|
569
|
+
message: "The conversation could not be recovered from its checkpoint.",
|
|
570
|
+
...(recoveryRecorded.record ? { recordId: recoveryRecorded.record.recordId } : {}),
|
|
571
|
+
...(recoveryRecorded.recordingError ? { recordingError: recoveryRecorded.recordingError } : {}),
|
|
572
|
+
cause: recoveryError,
|
|
438
573
|
});
|
|
439
|
-
if (recovery?.onLoadFailure !== "recover" || !classification.missing) throw structuredError();
|
|
440
|
-
config.onRecoveryProgress?.({ stage: "load_failed" });
|
|
441
|
-
config.onRecoveryProgress?.({ stage: "loading_checkpoint" });
|
|
442
|
-
const checkpoint = await this.agent.persistence.recoveryCheckpoints?.latest(id);
|
|
443
|
-
if (!checkpoint) throw structuredError();
|
|
444
|
-
config.onRecoveryProgress?.({ stage: "loading_checkpoint", checkpointId: checkpoint.checkpointId });
|
|
445
|
-
const recoveryAttemptId = `recovery-${randomUUID()}`;
|
|
446
|
-
try {
|
|
447
|
-
const seed = await buildRecoverySeed(
|
|
448
|
-
this.agent.persistence.messages,
|
|
449
|
-
id,
|
|
450
|
-
checkpoint,
|
|
451
|
-
summary.latestSequence,
|
|
452
|
-
recovery,
|
|
453
|
-
);
|
|
454
|
-
config.onRecoveryProgress?.({ stage: "creating_session", checkpointId: checkpoint.checkpointId });
|
|
455
|
-
const conversation = await this.start(id, summary.participants, {
|
|
456
|
-
...startConfig,
|
|
457
|
-
providerSession: "new",
|
|
458
|
-
settings,
|
|
459
|
-
});
|
|
460
|
-
try {
|
|
461
|
-
config.onRecoveryProgress?.({ stage: "seeding", checkpointId: checkpoint.checkpointId });
|
|
462
|
-
await conversation.seedRecoveryContext(seed.prompt);
|
|
463
|
-
const acknowledgement = await this.persistProviderSession(conversation, id, {
|
|
464
|
-
transitionId: recoveryAttemptId,
|
|
465
|
-
metadata: JSON.stringify({
|
|
466
|
-
recoveryCheckpointId: checkpoint.checkpointId,
|
|
467
|
-
previousInternalSessionId: active.internalSessionId,
|
|
468
|
-
recoveredThroughSequence: seed.recoveredThroughSequence,
|
|
469
|
-
}),
|
|
470
|
-
}, true);
|
|
471
|
-
conversation.acknowledgeProviderAttachment(acknowledgement);
|
|
472
|
-
} catch (recoveryError) {
|
|
473
|
-
this.live.delete(id);
|
|
474
|
-
await conversation.stop().catch(() => undefined);
|
|
475
|
-
throw recoveryError;
|
|
476
|
-
}
|
|
477
|
-
const result: ConversationRecoveryResult = Object.freeze({
|
|
478
|
-
checkpointId: checkpoint.checkpointId,
|
|
479
|
-
coveredSequence: checkpoint.coveredSequence,
|
|
480
|
-
recoveredThroughSequence: seed.recoveredThroughSequence,
|
|
481
|
-
previousInternalSessionId: active.internalSessionId,
|
|
482
|
-
newInternalSessionId: conversation.internalSessionId!,
|
|
483
|
-
});
|
|
484
|
-
config.onRecoveryProgress?.({ stage: "completed", checkpointId: checkpoint.checkpointId });
|
|
485
|
-
return Object.freeze({ conversation, providerSession: "recovered", recovery: result });
|
|
486
|
-
} catch (recoveryError) {
|
|
487
|
-
// A recovery failure is a distinct root cause from the load failure already
|
|
488
|
-
// recorded above; it prevents the logical conversation from reopening.
|
|
489
|
-
const recoveryRecorded = await this.recordConversationError({
|
|
490
|
-
settings,
|
|
491
|
-
agentConversationId: id,
|
|
492
|
-
attemptId: recoveryAttemptId,
|
|
493
|
-
source: "recovery",
|
|
494
|
-
code: "recovery_failed",
|
|
495
|
-
recoverability: "recoverable",
|
|
496
|
-
message: "The conversation could not be recovered from its checkpoint.",
|
|
497
|
-
transitionId: recoveryAttemptId,
|
|
498
|
-
internalSessionId: active.internalSessionId,
|
|
499
|
-
});
|
|
500
|
-
throw new ProviderSessionError({
|
|
501
|
-
agentSessionId: this.agent.id,
|
|
502
|
-
agentConversationId: id,
|
|
503
|
-
attemptId: recoveryAttemptId,
|
|
504
|
-
internalSessionId: active.internalSessionId,
|
|
505
|
-
code: "recovery_failed",
|
|
506
|
-
source: "recovery",
|
|
507
|
-
recoverability: "recoverable",
|
|
508
|
-
message: "The conversation could not be recovered from its checkpoint.",
|
|
509
|
-
...(recoveryRecorded.record ? { recordId: recoveryRecorded.record.recordId } : {}),
|
|
510
|
-
...(recoveryRecorded.recordingError ? { recordingError: recoveryRecorded.recordingError } : {}),
|
|
511
|
-
cause: recoveryError,
|
|
512
|
-
});
|
|
513
|
-
}
|
|
514
574
|
}
|
|
515
575
|
}
|
|
516
576
|
|
|
@@ -571,6 +631,8 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
571
631
|
? (await this.agent.persistence.recoveryCheckpoints?.deleteForConversation?.(id)) ?? 0
|
|
572
632
|
: 0;
|
|
573
633
|
await this.agent.persistence.conversations.delete(id, deletedAt);
|
|
634
|
+
// A deleted conversation runs no next turn, so its waiting out-of-band parts would never leave.
|
|
635
|
+
forgetPendingParts(this.agent, id);
|
|
574
636
|
let providerDeleted: boolean | "unsupported" = false;
|
|
575
637
|
if (active) {
|
|
576
638
|
providerDeleted = await deleteProviderSession({
|
|
@@ -595,46 +657,81 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
595
657
|
if (!this.agent.persistence.records.deleteForConversation) {
|
|
596
658
|
throw new Error("this persistence backend cannot clear a transcript");
|
|
597
659
|
}
|
|
598
|
-
|
|
660
|
+
const result = await this.agent.persistence.transaction(async (persistence) => {
|
|
599
661
|
const recordsDeleted = await persistence.records.deleteForConversation!(id);
|
|
600
662
|
const checkpointsDeleted = options.checkpoints
|
|
601
663
|
? (await persistence.recoveryCheckpoints?.deleteForConversation?.(id)) ?? 0
|
|
602
664
|
: 0;
|
|
603
665
|
return Object.freeze({ recordsDeleted, checkpointsDeleted });
|
|
604
666
|
});
|
|
667
|
+
// The backend store's copies went with the records; a consumer store is cleaned here.
|
|
668
|
+
if (this.agent.media.store) await this.agent.deleteMediaForConversation(id);
|
|
669
|
+
else forgetPendingParts(this.agent, id);
|
|
670
|
+
return result;
|
|
605
671
|
}
|
|
606
672
|
|
|
607
673
|
async appendAssistantMessage(
|
|
608
674
|
id: AgentConversationId,
|
|
609
675
|
input: AppendAssistantMessageInput,
|
|
610
676
|
): Promise<MessageRecord> {
|
|
611
|
-
|
|
677
|
+
const parts = promptParts(input) ?? [{ kind: "text" as const, text: input.text ?? "" }];
|
|
678
|
+
const hasMedia = parts.some((part) => part.kind !== "text" && part.kind !== "pasted");
|
|
679
|
+
if (!partsText(parts).trim() && !hasMedia) {
|
|
612
680
|
throw new Error("assistant message text cannot be blank");
|
|
613
681
|
}
|
|
614
682
|
const summary = await this.agent.persistence.conversations.get(id);
|
|
615
683
|
if (!summary || summary.deletedAt) throw new Error(`unknown active conversation: ${id}`);
|
|
616
684
|
const settings = this.writeSettings(summary);
|
|
617
685
|
const level = settings.capture.message;
|
|
618
|
-
if (level !== "content" && level !== "raw") {
|
|
686
|
+
if (!hasMedia && level !== "content" && level !== "raw") {
|
|
619
687
|
throw new Error(
|
|
620
688
|
`appending an assistant message requires message capture "content" or "raw", not "${level}"`,
|
|
621
689
|
);
|
|
622
690
|
}
|
|
691
|
+
// No agent reads the parts yet: every kind is accepted now, and delivery names what the agent of
|
|
692
|
+
// the next turn cannot take.
|
|
693
|
+
const resolved = await resolveParts(parts, {
|
|
694
|
+
cwd: this.live.get(id)?.cwd ?? this.settings.defaults.cwd ?? process.cwd(),
|
|
695
|
+
capabilities: { image: true, audio: true, embeddedContext: true },
|
|
696
|
+
thresholds: this.agent.media.thresholds,
|
|
697
|
+
owner: id,
|
|
698
|
+
store: this.agent.media.store ?? this.agent.persistence.media,
|
|
699
|
+
});
|
|
623
700
|
const appendId = `append-${randomUUID()}`;
|
|
624
|
-
const [
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
701
|
+
const persisted: ConversationRecord[] = [];
|
|
702
|
+
const recordId = `${appendId}:assistant`;
|
|
703
|
+
await this.agent.persistence.transaction(async (scope) => {
|
|
704
|
+
const content = await persistParts(resolved, id, this.agent.media.store ?? scope.media, settings.capture.media);
|
|
705
|
+
await persistObservationsInTransaction(settings, scope, [{
|
|
706
|
+
recordId,
|
|
707
|
+
agentSessionId: this.agent.id,
|
|
708
|
+
agentConversationId: id,
|
|
709
|
+
kind: "message",
|
|
710
|
+
timestamp: new Date().toISOString(),
|
|
711
|
+
// A standalone message at its observed sequence, without a provider operation.
|
|
712
|
+
role: "assistant",
|
|
713
|
+
logicalMessageId: `message:${appendId}:assistant`,
|
|
714
|
+
...(input.consumerMetadata !== undefined ? { consumerMetadata: input.consumerMetadata } : {}),
|
|
715
|
+
content,
|
|
716
|
+
status: "completed",
|
|
717
|
+
metadata: JSON.stringify({ origin: OUT_OF_BAND_MESSAGE_ORIGIN, appendId }),
|
|
718
|
+
}], true, persisted);
|
|
719
|
+
});
|
|
720
|
+
const record = persisted[0];
|
|
637
721
|
if (record?.kind !== "message") throw new Error("assistant message was not persisted");
|
|
722
|
+
// The next turn delivers the message from its record. When the record cannot restore it (a part
|
|
723
|
+
// not recorded, media left out by capture, a copy not kept, text not captured), its parts wait in
|
|
724
|
+
// memory instead.
|
|
725
|
+
const blocks = Array.isArray(record.content) ? record.content : [];
|
|
726
|
+
const media = resolved.filter(isMediaPart);
|
|
727
|
+
const restorable = (level === "content" || level === "raw")
|
|
728
|
+
&& resolved.every((part) => part.record !== false)
|
|
729
|
+
&& blocks.filter((block) => block.type === "media").length === media.length
|
|
730
|
+
&& blocks.filter((block) => block.type === "media" && block.ref).length
|
|
731
|
+
=== media.filter((part) => part.mode === "copy").length;
|
|
732
|
+
if (!restorable) pendingOutOfBandParts(this.agent).set(recordId, { owner: id, parts: resolved });
|
|
733
|
+
this.agent.publishCommittedRecords(persisted);
|
|
734
|
+
if (settings.auditLog) this.agent.audit?.notifyPending();
|
|
638
735
|
await updateConversationIdentity(this.agent, settings, id, [record]);
|
|
639
736
|
return record;
|
|
640
737
|
}
|
|
@@ -779,6 +876,17 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
779
876
|
id,
|
|
780
877
|
participants,
|
|
781
878
|
config.settings,
|
|
879
|
+
async (loadError) => {
|
|
880
|
+
const current = conversation!;
|
|
881
|
+
await this.recoverAfterLoadFailure(id, current.internalSessionId!, loadError, config.settings, {},
|
|
882
|
+
async () => {
|
|
883
|
+
await current.restartProviderFresh();
|
|
884
|
+
return current;
|
|
885
|
+
},
|
|
886
|
+
async () => {
|
|
887
|
+
await current.connection.forceStop();
|
|
888
|
+
});
|
|
889
|
+
},
|
|
782
890
|
);
|
|
783
891
|
this.liveSettings.set(id, config.settings);
|
|
784
892
|
conversation = await AgentConversation.create({
|
|
@@ -875,45 +983,7 @@ export class DefaultAgentConversationManager implements AgentConversationManager
|
|
|
875
983
|
readonly internalSessionId?: string;
|
|
876
984
|
readonly details?: ConversationErrorDetails;
|
|
877
985
|
}): Promise<{ readonly record?: ConversationRecord; readonly recordingError?: Error }> {
|
|
878
|
-
|
|
879
|
-
recordId: `${input.attemptId}:error`,
|
|
880
|
-
agentSessionId: this.agent.id,
|
|
881
|
-
agentConversationId: input.agentConversationId,
|
|
882
|
-
kind: "error",
|
|
883
|
-
timestamp: new Date().toISOString(),
|
|
884
|
-
source: input.source,
|
|
885
|
-
code: input.code,
|
|
886
|
-
recoverability: input.recoverability,
|
|
887
|
-
...(input.message === undefined ? {} : { message: input.message }),
|
|
888
|
-
...(input.operationId === undefined ? {} : { operationId: input.operationId }),
|
|
889
|
-
...(input.transitionId === undefined ? {} : { transitionId: input.transitionId }),
|
|
890
|
-
...(input.internalSessionId === undefined ? {} : { internalSessionId: input.internalSessionId }),
|
|
891
|
-
...(input.details === undefined ? {} : { details: input.details }),
|
|
892
|
-
};
|
|
893
|
-
const settings = input.settings ?? this.settings;
|
|
894
|
-
const level = settings.capture.error;
|
|
895
|
-
const audit = settings.auditLog;
|
|
896
|
-
let persisted: ConversationRecord | undefined;
|
|
897
|
-
try {
|
|
898
|
-
await this.agent.persistence.transaction(async (persistence) => {
|
|
899
|
-
if (level !== "none") {
|
|
900
|
-
persisted = await persistence.records.append(captureRuntimeRecord(record, level));
|
|
901
|
-
}
|
|
902
|
-
if (audit) {
|
|
903
|
-
await enqueueAuditObservation(persistence, {
|
|
904
|
-
scope: "conversation",
|
|
905
|
-
sourceObservationId: record.recordId,
|
|
906
|
-
...(input.operationId === undefined ? {} : { operationId: input.operationId }),
|
|
907
|
-
record,
|
|
908
|
-
}, audit);
|
|
909
|
-
}
|
|
910
|
-
});
|
|
911
|
-
} catch (error) {
|
|
912
|
-
return { recordingError: error instanceof Error ? error : new Error(String(error)) };
|
|
913
|
-
}
|
|
914
|
-
if (persisted) this.agent.publishCommittedRecords([persisted]);
|
|
915
|
-
if (audit) this.agent.audit?.notifyPending();
|
|
916
|
-
return persisted ? { record: persisted } : {};
|
|
986
|
+
return writeConversationError(this.agent, this.settings, input);
|
|
917
987
|
}
|
|
918
988
|
|
|
919
989
|
/**
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { Agent } from "../agent.ts";
|
|
2
|
+
import type { AgentConversationId } from "../agent-ids.ts";
|
|
3
|
+
import type {
|
|
4
|
+
ConversationErrorDetails,
|
|
5
|
+
ConversationErrorRecoverability,
|
|
6
|
+
ConversationErrorSource,
|
|
7
|
+
ConversationRecord,
|
|
8
|
+
NewConversationRecord,
|
|
9
|
+
} from "../persistence/backend.ts";
|
|
10
|
+
import type { ManagerSettings } from "./manager-settings.ts";
|
|
11
|
+
import { captureRuntimeRecord, enqueueAuditObservation } from "./record-capture.ts";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Write one conversation error record, and its audit observation when audit logging is on, then
|
|
15
|
+
* publish it. A failure to record is returned, not thrown, so the caller's own error still surfaces.
|
|
16
|
+
*/
|
|
17
|
+
export async function writeConversationError(
|
|
18
|
+
agent: Agent,
|
|
19
|
+
defaults: ManagerSettings,
|
|
20
|
+
input: {
|
|
21
|
+
/**
|
|
22
|
+
* The conversation's own settings; the Agent's when the record is not about one conversation's
|
|
23
|
+
* start.
|
|
24
|
+
*/
|
|
25
|
+
readonly settings?: ManagerSettings;
|
|
26
|
+
readonly agentConversationId: AgentConversationId;
|
|
27
|
+
readonly attemptId: string;
|
|
28
|
+
readonly source: ConversationErrorSource;
|
|
29
|
+
readonly code: string;
|
|
30
|
+
readonly recoverability: ConversationErrorRecoverability;
|
|
31
|
+
readonly message?: string;
|
|
32
|
+
readonly operationId?: string;
|
|
33
|
+
readonly transitionId?: string;
|
|
34
|
+
readonly internalSessionId?: string;
|
|
35
|
+
readonly details?: ConversationErrorDetails;
|
|
36
|
+
},
|
|
37
|
+
): Promise<{ readonly record?: ConversationRecord; readonly recordingError?: Error }> {
|
|
38
|
+
const record: NewConversationRecord = {
|
|
39
|
+
recordId: `${input.attemptId}:error`,
|
|
40
|
+
agentSessionId: agent.id,
|
|
41
|
+
agentConversationId: input.agentConversationId,
|
|
42
|
+
kind: "error",
|
|
43
|
+
timestamp: new Date().toISOString(),
|
|
44
|
+
source: input.source,
|
|
45
|
+
code: input.code,
|
|
46
|
+
recoverability: input.recoverability,
|
|
47
|
+
...(input.message === undefined ? {} : { message: input.message }),
|
|
48
|
+
...(input.operationId === undefined ? {} : { operationId: input.operationId }),
|
|
49
|
+
...(input.transitionId === undefined ? {} : { transitionId: input.transitionId }),
|
|
50
|
+
...(input.internalSessionId === undefined ? {} : { internalSessionId: input.internalSessionId }),
|
|
51
|
+
...(input.details === undefined ? {} : { details: input.details }),
|
|
52
|
+
};
|
|
53
|
+
const settings = input.settings ?? defaults;
|
|
54
|
+
const level = settings.capture.error;
|
|
55
|
+
const audit = settings.auditLog;
|
|
56
|
+
let persisted: ConversationRecord | undefined;
|
|
57
|
+
try {
|
|
58
|
+
await agent.persistence.transaction(async (persistence) => {
|
|
59
|
+
if (level !== "none") {
|
|
60
|
+
persisted = await persistence.records.append(captureRuntimeRecord(record, level));
|
|
61
|
+
}
|
|
62
|
+
if (audit) {
|
|
63
|
+
await enqueueAuditObservation(persistence, {
|
|
64
|
+
scope: "conversation",
|
|
65
|
+
sourceObservationId: record.recordId,
|
|
66
|
+
...(input.operationId === undefined ? {} : { operationId: input.operationId }),
|
|
67
|
+
record,
|
|
68
|
+
}, audit);
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
} catch (error) {
|
|
72
|
+
return { recordingError: error instanceof Error ? error : new Error(String(error)) };
|
|
73
|
+
}
|
|
74
|
+
if (persisted) agent.publishCommittedRecords([persisted]);
|
|
75
|
+
if (audit) agent.audit?.notifyPending();
|
|
76
|
+
return persisted ? { record: persisted } : {};
|
|
77
|
+
}
|