@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
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
export interface ConversationCheckpointSchedule {
|
|
2
|
+
/** One-based successful response counts. Defaults to 1, 5, 10, 15, 30, and 50. */
|
|
3
|
+
readonly milestones?: readonly number[];
|
|
4
|
+
/** After the final milestone, generate every N successful responses. Defaults to 50. */
|
|
5
|
+
readonly everyAfterMilestones?: number;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface ConversationCheckpointingConfig {
|
|
9
|
+
readonly enabled?: boolean;
|
|
10
|
+
readonly schedule?: ConversationCheckpointSchedule;
|
|
11
|
+
readonly summaryInstruction?: string;
|
|
12
|
+
readonly recovery?: ConversationRecoveryConfig;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface ConversationRecoveryConfig {
|
|
16
|
+
readonly onLoadFailure?: "recover" | "error";
|
|
17
|
+
/** ACP has no standardized missing-session error, so consumers may override detection. */
|
|
18
|
+
readonly isMissingProviderSession?: (error: unknown) => boolean;
|
|
19
|
+
readonly seedInstruction?: string;
|
|
20
|
+
readonly maxTailMessages?: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface ResolvedConversationCheckpointingConfig {
|
|
24
|
+
readonly enabled: boolean;
|
|
25
|
+
readonly milestones: readonly number[];
|
|
26
|
+
readonly everyAfterMilestones: number;
|
|
27
|
+
readonly summaryInstruction: string;
|
|
28
|
+
readonly recovery: ResolvedConversationRecoveryConfig;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface ResolvedConversationRecoveryConfig {
|
|
32
|
+
readonly onLoadFailure: "recover" | "error";
|
|
33
|
+
readonly isMissingProviderSession?: (error: unknown) => boolean;
|
|
34
|
+
readonly seedInstruction: string;
|
|
35
|
+
readonly maxTailMessages: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const DEFAULT_MILESTONES = Object.freeze([1, 5, 10, 15, 30, 50]);
|
|
39
|
+
|
|
40
|
+
export function resolveConversationCheckpointingConfig(
|
|
41
|
+
config: ConversationCheckpointingConfig = {},
|
|
42
|
+
): ResolvedConversationCheckpointingConfig {
|
|
43
|
+
const milestones = [...(config.schedule?.milestones ?? DEFAULT_MILESTONES)];
|
|
44
|
+
if (
|
|
45
|
+
milestones.length === 0
|
|
46
|
+
|| milestones.some((value) => !Number.isSafeInteger(value) || value < 1)
|
|
47
|
+
|| milestones.some((value, index) => index > 0 && value <= milestones[index - 1]!)
|
|
48
|
+
) throw new Error("checkpoint milestones must be strictly increasing positive integers");
|
|
49
|
+
const everyAfterMilestones = config.schedule?.everyAfterMilestones ?? 50;
|
|
50
|
+
if (!Number.isSafeInteger(everyAfterMilestones) || everyAfterMilestones < 1) {
|
|
51
|
+
throw new Error("checkpoint everyAfterMilestones must be a positive integer");
|
|
52
|
+
}
|
|
53
|
+
const summaryInstruction = config.summaryInstruction?.trim() || [
|
|
54
|
+
"Create a precise continuation summary for another instance of this agent.",
|
|
55
|
+
"Preserve objectives, decisions, important facts, unresolved questions, pending actions,",
|
|
56
|
+
"relevant resources, and the latest conversational state. Do not invent information.",
|
|
57
|
+
"Return only the continuation summary.",
|
|
58
|
+
].join(" ");
|
|
59
|
+
const maxTailMessages = config.recovery?.maxTailMessages ?? 100;
|
|
60
|
+
if (!Number.isSafeInteger(maxTailMessages) || maxTailMessages < 0 || maxTailMessages > 10_000) {
|
|
61
|
+
throw new Error("checkpoint recovery maxTailMessages must be between 0 and 10000");
|
|
62
|
+
}
|
|
63
|
+
return Object.freeze({
|
|
64
|
+
enabled: config.enabled ?? true,
|
|
65
|
+
milestones: Object.freeze(milestones),
|
|
66
|
+
everyAfterMilestones,
|
|
67
|
+
summaryInstruction,
|
|
68
|
+
recovery: Object.freeze({
|
|
69
|
+
onLoadFailure: config.recovery?.onLoadFailure ?? "recover",
|
|
70
|
+
...(config.recovery?.isMissingProviderSession
|
|
71
|
+
? { isMissingProviderSession: config.recovery.isMissingProviderSession }
|
|
72
|
+
: {}),
|
|
73
|
+
seedInstruction: config.recovery?.seedInstruction?.trim() || [
|
|
74
|
+
"Restore the following private continuation context for this conversation.",
|
|
75
|
+
"Do not answer it as a user request. Use it to continue naturally when the next user message arrives.",
|
|
76
|
+
].join(" "),
|
|
77
|
+
maxTailMessages,
|
|
78
|
+
}),
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function isConversationCheckpointDue(
|
|
83
|
+
successfulResponseCount: number,
|
|
84
|
+
config: ResolvedConversationCheckpointingConfig,
|
|
85
|
+
): boolean {
|
|
86
|
+
if (!config.enabled || successfulResponseCount < 1) return false;
|
|
87
|
+
if (config.milestones.includes(successfulResponseCount)) return true;
|
|
88
|
+
const last = config.milestones.at(-1)!;
|
|
89
|
+
return successfulResponseCount > last
|
|
90
|
+
&& (successfulResponseCount - last) % config.everyAfterMilestones === 0;
|
|
91
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { AgentConversationId } from "../agent-ids.ts";
|
|
2
|
+
import type { InternalInferenceId } from "../internal-inference/contracts.ts";
|
|
3
|
+
|
|
4
|
+
export type ConversationRecoveryCheckpointId = `chk-${string}`;
|
|
5
|
+
|
|
6
|
+
export interface ConversationRecoveryCheckpoint {
|
|
7
|
+
readonly checkpointId: ConversationRecoveryCheckpointId;
|
|
8
|
+
readonly agentConversationId: AgentConversationId;
|
|
9
|
+
readonly revision: number;
|
|
10
|
+
readonly coveredSequence: number;
|
|
11
|
+
readonly previousCheckpointId?: ConversationRecoveryCheckpointId;
|
|
12
|
+
readonly generatorInternalInferenceId: InternalInferenceId;
|
|
13
|
+
readonly summary: string;
|
|
14
|
+
readonly createdAt: string;
|
|
15
|
+
readonly metadata?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface PublishConversationRecoveryCheckpointInput {
|
|
19
|
+
readonly checkpointId: ConversationRecoveryCheckpointId;
|
|
20
|
+
readonly agentConversationId: AgentConversationId;
|
|
21
|
+
readonly coveredSequence: number;
|
|
22
|
+
readonly previousCheckpointId?: ConversationRecoveryCheckpointId;
|
|
23
|
+
readonly generatorInternalInferenceId: InternalInferenceId;
|
|
24
|
+
readonly summary: string;
|
|
25
|
+
readonly createdAt?: string;
|
|
26
|
+
readonly metadata?: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface ConversationRecoveryCheckpointListOptions {
|
|
30
|
+
readonly limit?: number;
|
|
31
|
+
readonly beforeRevision?: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface ConversationRecoveryCheckpointRepository {
|
|
35
|
+
/** Count completed provider turns using the stable operation ID on assistant messages. */
|
|
36
|
+
successfulResponseCount(agentConversationId: AgentConversationId): Promise<number>;
|
|
37
|
+
latestMessageSequence(agentConversationId: AgentConversationId): Promise<number>;
|
|
38
|
+
latest(agentConversationId: AgentConversationId): Promise<ConversationRecoveryCheckpoint | null>;
|
|
39
|
+
get(checkpointId: ConversationRecoveryCheckpointId): Promise<ConversationRecoveryCheckpoint | null>;
|
|
40
|
+
list(
|
|
41
|
+
agentConversationId: AgentConversationId,
|
|
42
|
+
options?: ConversationRecoveryCheckpointListOptions,
|
|
43
|
+
): Promise<readonly ConversationRecoveryCheckpoint[]>;
|
|
44
|
+
publish(input: PublishConversationRecoveryCheckpointInput): Promise<ConversationRecoveryCheckpoint>;
|
|
45
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import type { AgentConversationId } from "../agent-ids.ts";
|
|
2
|
+
import type { InternalInferenceManager } from "../internal-inference/contracts.ts";
|
|
3
|
+
import type { PersistenceBackend } from "../persistence/backend.ts";
|
|
4
|
+
import type { ConversationRecoveryCheckpoint } from "./contracts.ts";
|
|
5
|
+
import type { ResolvedConversationCheckpointingConfig } from "./config.ts";
|
|
6
|
+
import { isConversationCheckpointDue } from "./config.ts";
|
|
7
|
+
import { CONVERSATION_CHECKPOINT_STRATEGY_ID } from "./strategy.ts";
|
|
8
|
+
|
|
9
|
+
/** Schedules rolling summaries without waiting for their provider execution. */
|
|
10
|
+
export class ConversationCheckpointCoordinator {
|
|
11
|
+
private readonly unsubscribe: () => void;
|
|
12
|
+
private closed = false;
|
|
13
|
+
|
|
14
|
+
constructor(
|
|
15
|
+
private readonly persistence: PersistenceBackend,
|
|
16
|
+
private readonly inferences: InternalInferenceManager,
|
|
17
|
+
private readonly config: ResolvedConversationCheckpointingConfig,
|
|
18
|
+
) {
|
|
19
|
+
this.unsubscribe = inferences.subscribe((event) => {
|
|
20
|
+
if (
|
|
21
|
+
event.snapshot.purpose === "conversation_checkpoint"
|
|
22
|
+
&& event.snapshot.status === "completed"
|
|
23
|
+
&& event.snapshot.agentConversationId
|
|
24
|
+
) void this.afterCheckpointCompleted(
|
|
25
|
+
event.rootId,
|
|
26
|
+
event.snapshot.agentConversationId,
|
|
27
|
+
).catch(() => undefined);
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async latest(conversationId: AgentConversationId): Promise<ConversationRecoveryCheckpoint | null> {
|
|
32
|
+
return await this.requireRepository().latest(conversationId);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async afterSuccessfulResponse(conversationId: AgentConversationId): Promise<void> {
|
|
36
|
+
await this.scheduleIfDue(conversationId);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async request(conversationId: AgentConversationId): Promise<void> {
|
|
40
|
+
await this.enqueueLatest(conversationId);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
close(): void {
|
|
44
|
+
if (this.closed) return;
|
|
45
|
+
this.closed = true;
|
|
46
|
+
this.unsubscribe();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
private async afterCheckpointCompleted(
|
|
50
|
+
rootId: Parameters<InternalInferenceManager["getRun"]>[0],
|
|
51
|
+
conversationId: AgentConversationId,
|
|
52
|
+
): Promise<void> {
|
|
53
|
+
if (this.closed) return;
|
|
54
|
+
const run = await this.inferences.getRun(rootId);
|
|
55
|
+
const requestedThrough = run?.snapshot.requestedThroughSequence ?? 0;
|
|
56
|
+
const coveredThrough = (await this.requireRepository().latest(conversationId))?.coveredSequence ?? 0;
|
|
57
|
+
if (requestedThrough > coveredThrough) {
|
|
58
|
+
await this.enqueueLatest(conversationId);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
await this.scheduleIfDue(conversationId);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
private async scheduleIfDue(conversationId: AgentConversationId): Promise<void> {
|
|
65
|
+
if (this.closed || !this.config.enabled) return;
|
|
66
|
+
const count = await this.requireRepository().successfulResponseCount(conversationId);
|
|
67
|
+
if (!isConversationCheckpointDue(count, this.config)) return;
|
|
68
|
+
await this.enqueueLatest(conversationId);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
private async enqueueLatest(conversationId: AgentConversationId): Promise<void> {
|
|
72
|
+
if (this.closed) return;
|
|
73
|
+
const conversation = await this.persistence.conversations.get(conversationId);
|
|
74
|
+
if (!conversation || conversation.deletedAt) return;
|
|
75
|
+
const repository = this.requireRepository();
|
|
76
|
+
const throughSequence = await repository.latestMessageSequence(conversationId);
|
|
77
|
+
if (throughSequence < 1) return;
|
|
78
|
+
const previous = await repository.latest(conversationId);
|
|
79
|
+
if (previous && previous.coveredSequence >= throughSequence) return;
|
|
80
|
+
await this.inferences.enqueue({
|
|
81
|
+
purpose: "conversation_checkpoint",
|
|
82
|
+
agentConversationId: conversationId,
|
|
83
|
+
input: {
|
|
84
|
+
strategyId: CONVERSATION_CHECKPOINT_STRATEGY_ID,
|
|
85
|
+
version: 1,
|
|
86
|
+
payload: { instruction: this.config.summaryInstruction },
|
|
87
|
+
},
|
|
88
|
+
...(previous ? { sourceCheckpointId: previous.checkpointId } : {}),
|
|
89
|
+
sourceFromSequence: previous?.coveredSequence ?? 0,
|
|
90
|
+
sourceThroughSequence: throughSequence,
|
|
91
|
+
requestedThroughSequence: throughSequence,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
private requireRepository() {
|
|
96
|
+
const repository = this.persistence.recoveryCheckpoints;
|
|
97
|
+
if (!repository) throw new Error("persistence does not support recovery checkpoints");
|
|
98
|
+
return repository;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import type { Database } from "bun:sqlite";
|
|
2
|
+
import type { AgentConversationId } from "../../agent-ids.ts";
|
|
3
|
+
import type { InternalInferenceId } from "../../internal-inference/contracts.ts";
|
|
4
|
+
import { PersistenceConflictError } from "../../persistence/backend.ts";
|
|
5
|
+
import type {
|
|
6
|
+
ConversationRecoveryCheckpoint,
|
|
7
|
+
ConversationRecoveryCheckpointId,
|
|
8
|
+
ConversationRecoveryCheckpointListOptions,
|
|
9
|
+
ConversationRecoveryCheckpointRepository,
|
|
10
|
+
PublishConversationRecoveryCheckpointInput,
|
|
11
|
+
} from "../contracts.ts";
|
|
12
|
+
|
|
13
|
+
type WriteRunner = <T>(work: () => T) => Promise<T>;
|
|
14
|
+
|
|
15
|
+
interface CheckpointRow {
|
|
16
|
+
checkpoint_id: string;
|
|
17
|
+
agent_conversation_id: string;
|
|
18
|
+
revision: number;
|
|
19
|
+
covered_sequence: number;
|
|
20
|
+
previous_checkpoint_id: string | null;
|
|
21
|
+
generator_internal_inference_id: string;
|
|
22
|
+
summary: string;
|
|
23
|
+
created_at: string;
|
|
24
|
+
metadata: string | null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class SqliteConversationRecoveryCheckpointRepository
|
|
28
|
+
implements ConversationRecoveryCheckpointRepository {
|
|
29
|
+
constructor(private readonly database: Database, private readonly runWrite: WriteRunner) {}
|
|
30
|
+
|
|
31
|
+
async successfulResponseCount(agentConversationId: AgentConversationId): Promise<number> {
|
|
32
|
+
const row = this.database.query<{ count: number }, [string]>(
|
|
33
|
+
`SELECT COUNT(DISTINCT r.operation_id) AS count
|
|
34
|
+
FROM conversation_records r
|
|
35
|
+
JOIN conversation_messages m ON m.record_row_id = r.row_id
|
|
36
|
+
WHERE r.agent_conversation_id = ? AND r.kind = 'message'
|
|
37
|
+
AND m.role = 'assistant'
|
|
38
|
+
AND m.status = 'completed'
|
|
39
|
+
AND r.operation_id IS NOT NULL`,
|
|
40
|
+
).get(agentConversationId);
|
|
41
|
+
return Number(row?.count ?? 0);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async latestMessageSequence(agentConversationId: AgentConversationId): Promise<number> {
|
|
45
|
+
const row = this.database.query<{ sequence: number }, [string]>(
|
|
46
|
+
`SELECT COALESCE(MAX(sequence), 0) AS sequence FROM conversation_records
|
|
47
|
+
WHERE agent_conversation_id = ? AND kind = 'message'`,
|
|
48
|
+
).get(agentConversationId);
|
|
49
|
+
return Number(row?.sequence ?? 0);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async latest(agentConversationId: AgentConversationId): Promise<ConversationRecoveryCheckpoint | null> {
|
|
53
|
+
const row = this.database.query<CheckpointRow, [string]>(
|
|
54
|
+
`SELECT * FROM conversation_recovery_checkpoints
|
|
55
|
+
WHERE agent_conversation_id = ? ORDER BY revision DESC LIMIT 1`,
|
|
56
|
+
).get(agentConversationId);
|
|
57
|
+
return row ? fromRow(row) : null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async get(checkpointId: ConversationRecoveryCheckpointId): Promise<ConversationRecoveryCheckpoint | null> {
|
|
61
|
+
const row = this.database.query<CheckpointRow, [string]>(
|
|
62
|
+
"SELECT * FROM conversation_recovery_checkpoints WHERE checkpoint_id = ?",
|
|
63
|
+
).get(checkpointId);
|
|
64
|
+
return row ? fromRow(row) : null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async list(
|
|
68
|
+
agentConversationId: AgentConversationId,
|
|
69
|
+
options: ConversationRecoveryCheckpointListOptions = {},
|
|
70
|
+
): Promise<readonly ConversationRecoveryCheckpoint[]> {
|
|
71
|
+
const limit = boundedLimit(options.limit ?? 100);
|
|
72
|
+
const rows = options.beforeRevision === undefined
|
|
73
|
+
? this.database.query<CheckpointRow, [string, number]>(
|
|
74
|
+
`SELECT * FROM conversation_recovery_checkpoints
|
|
75
|
+
WHERE agent_conversation_id = ? ORDER BY revision DESC LIMIT ?`,
|
|
76
|
+
).all(agentConversationId, limit)
|
|
77
|
+
: this.database.query<CheckpointRow, [string, number, number]>(
|
|
78
|
+
`SELECT * FROM conversation_recovery_checkpoints
|
|
79
|
+
WHERE agent_conversation_id = ? AND revision < ? ORDER BY revision DESC LIMIT ?`,
|
|
80
|
+
).all(agentConversationId, options.beforeRevision, limit);
|
|
81
|
+
return Object.freeze(rows.map(fromRow));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async publish(input: PublishConversationRecoveryCheckpointInput): Promise<ConversationRecoveryCheckpoint> {
|
|
85
|
+
return await this.runWrite(() => {
|
|
86
|
+
const summary = input.summary.trim();
|
|
87
|
+
if (!summary) throw new Error("recovery checkpoint summary cannot be blank");
|
|
88
|
+
if (!Number.isSafeInteger(input.coveredSequence) || input.coveredSequence < 1) {
|
|
89
|
+
throw new Error("recovery checkpoint coveredSequence must be a positive integer");
|
|
90
|
+
}
|
|
91
|
+
const existing = this.database.query<CheckpointRow, [string]>(
|
|
92
|
+
"SELECT * FROM conversation_recovery_checkpoints WHERE checkpoint_id = ?",
|
|
93
|
+
).get(input.checkpointId);
|
|
94
|
+
if (existing) {
|
|
95
|
+
const checkpoint = fromRow(existing);
|
|
96
|
+
if (
|
|
97
|
+
checkpoint.agentConversationId !== input.agentConversationId
|
|
98
|
+
|| checkpoint.coveredSequence !== input.coveredSequence
|
|
99
|
+
|| checkpoint.generatorInternalInferenceId !== input.generatorInternalInferenceId
|
|
100
|
+
|| checkpoint.summary !== summary
|
|
101
|
+
) throw new PersistenceConflictError(`recovery checkpoint id conflict: ${input.checkpointId}`);
|
|
102
|
+
return checkpoint;
|
|
103
|
+
}
|
|
104
|
+
const latest = this.database.query<CheckpointRow, [string]>(
|
|
105
|
+
`SELECT * FROM conversation_recovery_checkpoints
|
|
106
|
+
WHERE agent_conversation_id = ? ORDER BY revision DESC LIMIT 1`,
|
|
107
|
+
).get(input.agentConversationId);
|
|
108
|
+
const previous = latest ? fromRow(latest) : null;
|
|
109
|
+
if ((previous?.checkpointId ?? undefined) !== input.previousCheckpointId) {
|
|
110
|
+
throw new PersistenceConflictError("recovery checkpoint previous version changed");
|
|
111
|
+
}
|
|
112
|
+
if (previous && input.coveredSequence <= previous.coveredSequence) {
|
|
113
|
+
throw new PersistenceConflictError("recovery checkpoint coverage must increase");
|
|
114
|
+
}
|
|
115
|
+
const revision = (previous?.revision ?? 0) + 1;
|
|
116
|
+
const createdAt = input.createdAt ?? new Date().toISOString();
|
|
117
|
+
this.database.query(
|
|
118
|
+
`INSERT INTO conversation_recovery_checkpoints(
|
|
119
|
+
checkpoint_id, agent_conversation_id, revision, covered_sequence,
|
|
120
|
+
previous_checkpoint_id, generator_internal_inference_id, summary, created_at, metadata
|
|
121
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
122
|
+
).run(
|
|
123
|
+
input.checkpointId,
|
|
124
|
+
input.agentConversationId,
|
|
125
|
+
revision,
|
|
126
|
+
input.coveredSequence,
|
|
127
|
+
input.previousCheckpointId ?? null,
|
|
128
|
+
input.generatorInternalInferenceId,
|
|
129
|
+
summary,
|
|
130
|
+
createdAt,
|
|
131
|
+
input.metadata ?? null,
|
|
132
|
+
);
|
|
133
|
+
return Object.freeze({ ...input, summary, revision, createdAt });
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function fromRow(row: CheckpointRow): ConversationRecoveryCheckpoint {
|
|
139
|
+
return Object.freeze({
|
|
140
|
+
checkpointId: row.checkpoint_id as ConversationRecoveryCheckpointId,
|
|
141
|
+
agentConversationId: row.agent_conversation_id as AgentConversationId,
|
|
142
|
+
revision: Number(row.revision),
|
|
143
|
+
coveredSequence: Number(row.covered_sequence),
|
|
144
|
+
...(row.previous_checkpoint_id
|
|
145
|
+
? { previousCheckpointId: row.previous_checkpoint_id as ConversationRecoveryCheckpointId }
|
|
146
|
+
: {}),
|
|
147
|
+
generatorInternalInferenceId: row.generator_internal_inference_id as InternalInferenceId,
|
|
148
|
+
summary: row.summary,
|
|
149
|
+
createdAt: row.created_at,
|
|
150
|
+
...(row.metadata ? { metadata: row.metadata } : {}),
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function boundedLimit(value: number): number {
|
|
155
|
+
if (!Number.isSafeInteger(value) || value < 1 || value > 1_000) {
|
|
156
|
+
throw new Error("recovery checkpoint limit must be an integer between 1 and 1000");
|
|
157
|
+
}
|
|
158
|
+
return value;
|
|
159
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import type { AgentConversationId } from "../agent-ids.ts";
|
|
2
|
+
import type { ConversationMessagePersistence } from "../persistence/backend.ts";
|
|
3
|
+
import type { ConversationRecoveryCheckpoint } from "./contracts.ts";
|
|
4
|
+
import type { ResolvedConversationRecoveryConfig } from "./config.ts";
|
|
5
|
+
|
|
6
|
+
export interface ConversationRecoveryProgress {
|
|
7
|
+
readonly stage: "load_failed" | "loading_checkpoint" | "creating_session" | "seeding" | "completed";
|
|
8
|
+
readonly checkpointId?: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface ConversationRecoveryResult {
|
|
12
|
+
readonly checkpointId: string;
|
|
13
|
+
readonly coveredSequence: number;
|
|
14
|
+
readonly recoveredThroughSequence: number;
|
|
15
|
+
readonly previousInternalSessionId: string;
|
|
16
|
+
readonly newInternalSessionId: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function isMissingProviderSessionError(
|
|
20
|
+
error: unknown,
|
|
21
|
+
override?: (error: unknown) => boolean,
|
|
22
|
+
): boolean {
|
|
23
|
+
if (override) return override(error);
|
|
24
|
+
const value = error as { code?: unknown; message?: unknown; data?: unknown } | null;
|
|
25
|
+
const message = typeof value?.message === "string" ? value.message : String(error);
|
|
26
|
+
const data = isRecord(value?.data) ? value.data : undefined;
|
|
27
|
+
// OpenCode's ACP adapter currently collapses a deleted session into this generic
|
|
28
|
+
// service error. The service discriminator is the only machine-readable signal it
|
|
29
|
+
// exposes, so keep the match deliberately exact and scoped to the session service.
|
|
30
|
+
if (
|
|
31
|
+
value?.code === -32603
|
|
32
|
+
&& message.toLowerCase() === "internal error: opencode service failure"
|
|
33
|
+
&& data?.service === "session"
|
|
34
|
+
) return true;
|
|
35
|
+
const text = [
|
|
36
|
+
message,
|
|
37
|
+
safeJson(value?.data),
|
|
38
|
+
].join(" ").toLowerCase();
|
|
39
|
+
return [
|
|
40
|
+
"failed to resolve rollout path",
|
|
41
|
+
"no rollout found for thread id",
|
|
42
|
+
"session not found",
|
|
43
|
+
"unknown session",
|
|
44
|
+
"no such session",
|
|
45
|
+
"session does not exist",
|
|
46
|
+
"file does not exist",
|
|
47
|
+
].some((pattern) => text.includes(pattern));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
51
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export async function buildRecoverySeed(
|
|
55
|
+
messages: ConversationMessagePersistence,
|
|
56
|
+
conversationId: AgentConversationId,
|
|
57
|
+
checkpoint: ConversationRecoveryCheckpoint,
|
|
58
|
+
latestSequence: number,
|
|
59
|
+
config: ResolvedConversationRecoveryConfig,
|
|
60
|
+
): Promise<{ readonly prompt: string; readonly recoveredThroughSequence: number }> {
|
|
61
|
+
const tail = await readTailMessages(
|
|
62
|
+
messages,
|
|
63
|
+
conversationId,
|
|
64
|
+
checkpoint.coveredSequence,
|
|
65
|
+
latestSequence,
|
|
66
|
+
config.maxTailMessages,
|
|
67
|
+
);
|
|
68
|
+
return Object.freeze({
|
|
69
|
+
prompt: [
|
|
70
|
+
config.seedInstruction,
|
|
71
|
+
`Continuation checkpoint through canonical sequence ${checkpoint.coveredSequence}:`,
|
|
72
|
+
checkpoint.summary,
|
|
73
|
+
tail.length
|
|
74
|
+
? `Canonical messages after the checkpoint:\n${JSON.stringify(tail)}`
|
|
75
|
+
: "There are no canonical messages after the checkpoint.",
|
|
76
|
+
].join("\n\n"),
|
|
77
|
+
recoveredThroughSequence: tail.at(-1)?.sequence ?? checkpoint.coveredSequence,
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function readTailMessages(
|
|
82
|
+
repository: ConversationMessagePersistence,
|
|
83
|
+
conversationId: AgentConversationId,
|
|
84
|
+
afterSequence: number,
|
|
85
|
+
throughSequence: number,
|
|
86
|
+
limit: number,
|
|
87
|
+
) {
|
|
88
|
+
if (limit === 0 || throughSequence <= afterSequence) return [];
|
|
89
|
+
const values: Array<{ sequence: number; role: string; participantId?: string; content: unknown }> = [];
|
|
90
|
+
let cursor: string | undefined;
|
|
91
|
+
do {
|
|
92
|
+
const page = await repository.list(conversationId, {
|
|
93
|
+
afterSequence,
|
|
94
|
+
throughSequence,
|
|
95
|
+
limit: Math.min(limit, 1_000),
|
|
96
|
+
...(cursor ? { cursor } : {}),
|
|
97
|
+
});
|
|
98
|
+
for (const message of page.messages) {
|
|
99
|
+
values.push({
|
|
100
|
+
sequence: message.sequence,
|
|
101
|
+
role: message.role,
|
|
102
|
+
...(message.participantId ? { participantId: message.participantId } : {}),
|
|
103
|
+
content: message.content,
|
|
104
|
+
});
|
|
105
|
+
if (values.length >= limit) return values;
|
|
106
|
+
}
|
|
107
|
+
cursor = page.nextCursor;
|
|
108
|
+
} while (cursor);
|
|
109
|
+
return values;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function safeJson(value: unknown): string {
|
|
113
|
+
try { return JSON.stringify(value) ?? ""; } catch { return ""; }
|
|
114
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { formatResponseMessages } from "../response.ts";
|
|
2
|
+
import type { ConversationRecord, PersistenceJsonValue } from "../persistence/backend.ts";
|
|
3
|
+
import type {
|
|
4
|
+
InternalInferenceCompletion,
|
|
5
|
+
InternalInferenceStrategy,
|
|
6
|
+
} from "../internal-inference/contracts.ts";
|
|
7
|
+
import { createConversationRecoveryCheckpointId } from "./ids.ts";
|
|
8
|
+
|
|
9
|
+
export const CONVERSATION_CHECKPOINT_STRATEGY_ID = "conversation-checkpoint-v1";
|
|
10
|
+
|
|
11
|
+
const CHECKPOINT_READ_ONLY_INSTRUCTION = [
|
|
12
|
+
"Do not execute commands, use tools, inspect files, or modify the environment.",
|
|
13
|
+
"Only summarize the records supplied in this prompt.",
|
|
14
|
+
].join(" ");
|
|
15
|
+
|
|
16
|
+
export type ConversationCheckpointPayload = {
|
|
17
|
+
readonly instruction: string;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export class ConversationCheckpointStrategy
|
|
21
|
+
implements InternalInferenceStrategy<ConversationCheckpointPayload> {
|
|
22
|
+
readonly strategyId = CONVERSATION_CHECKPOINT_STRATEGY_ID;
|
|
23
|
+
readonly purpose = "conversation_checkpoint" as const;
|
|
24
|
+
readonly version = 1;
|
|
25
|
+
|
|
26
|
+
validatePayload(payload: PersistenceJsonValue): ConversationCheckpointPayload {
|
|
27
|
+
const instruction = (payload as { instruction?: unknown })?.instruction;
|
|
28
|
+
if (typeof instruction !== "string" || !instruction.trim()) {
|
|
29
|
+
throw new Error("conversation checkpoint instruction is required");
|
|
30
|
+
}
|
|
31
|
+
return Object.freeze({ instruction: instruction.trim() });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async prepare(context: Parameters<InternalInferenceStrategy<ConversationCheckpointPayload>["prepare"]>[0], payload: ConversationCheckpointPayload) {
|
|
35
|
+
const conversationId = context.attempt.agentConversationId;
|
|
36
|
+
const through = context.attempt.sourceThroughSequence;
|
|
37
|
+
if (!conversationId || through === undefined) {
|
|
38
|
+
throw new Error("conversation checkpoint requires a conversation and source coverage");
|
|
39
|
+
}
|
|
40
|
+
const repository = context.persistence.recoveryCheckpoints;
|
|
41
|
+
if (!repository) throw new Error("persistence does not support recovery checkpoints");
|
|
42
|
+
const previous = await repository.latest(conversationId);
|
|
43
|
+
if ((previous?.checkpointId ?? undefined) !== context.attempt.sourceCheckpointId) {
|
|
44
|
+
throw new Error("conversation checkpoint source changed before preparation");
|
|
45
|
+
}
|
|
46
|
+
const from = previous?.coveredSequence ?? 0;
|
|
47
|
+
if (through <= from) throw new Error("conversation checkpoint source range is empty");
|
|
48
|
+
const records = await readRecords(context.persistence.records, conversationId, from, through);
|
|
49
|
+
if (!records.length) throw new Error("conversation checkpoint source contains no records");
|
|
50
|
+
return Object.freeze({
|
|
51
|
+
prompt: [
|
|
52
|
+
payload.instruction,
|
|
53
|
+
CHECKPOINT_READ_ONLY_INSTRUCTION,
|
|
54
|
+
previous
|
|
55
|
+
? `Previous continuation summary:\n${previous.summary}`
|
|
56
|
+
: "There is no previous continuation summary.",
|
|
57
|
+
`New canonical records after sequence ${from} through ${through}:`,
|
|
58
|
+
JSON.stringify(records),
|
|
59
|
+
].join("\n\n"),
|
|
60
|
+
metadata: JSON.stringify({ previousCheckpointId: previous?.checkpointId ?? null, through }),
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async complete(context: Parameters<InternalInferenceStrategy<ConversationCheckpointPayload>["complete"]>[0], result: Parameters<InternalInferenceStrategy<ConversationCheckpointPayload>["complete"]>[1]): Promise<InternalInferenceCompletion> {
|
|
65
|
+
const conversationId = context.attempt.agentConversationId;
|
|
66
|
+
const through = context.attempt.sourceThroughSequence;
|
|
67
|
+
if (!conversationId || through === undefined) throw new Error("checkpoint completion lacks source scope");
|
|
68
|
+
const repository = context.persistence.recoveryCheckpoints;
|
|
69
|
+
if (!repository) throw new Error("persistence does not support recovery checkpoints");
|
|
70
|
+
const summary = formatResponseMessages(result.messages, "\n\n").trim();
|
|
71
|
+
if (!summary) throw new Error("checkpoint inference returned an empty summary");
|
|
72
|
+
const checkpoint = await repository.publish({
|
|
73
|
+
checkpointId: createConversationRecoveryCheckpointId(),
|
|
74
|
+
agentConversationId: conversationId,
|
|
75
|
+
coveredSequence: through,
|
|
76
|
+
...(context.attempt.sourceCheckpointId
|
|
77
|
+
? { previousCheckpointId: context.attempt.sourceCheckpointId as `chk-${string}` }
|
|
78
|
+
: {}),
|
|
79
|
+
generatorInternalInferenceId: result.internalInferenceId,
|
|
80
|
+
summary,
|
|
81
|
+
});
|
|
82
|
+
await context.persistence.records.append({
|
|
83
|
+
recordId: `${result.internalInferenceId}:checkpoint`,
|
|
84
|
+
agentSessionId: context.attempt.agentSessionId,
|
|
85
|
+
agentConversationId: conversationId,
|
|
86
|
+
kind: "native_action",
|
|
87
|
+
timestamp: checkpoint.createdAt,
|
|
88
|
+
action: "conversation_checkpoint",
|
|
89
|
+
state: "completed",
|
|
90
|
+
output: {
|
|
91
|
+
internalInferenceId: result.internalInferenceId,
|
|
92
|
+
checkpointId: checkpoint.checkpointId,
|
|
93
|
+
coveredSequence: checkpoint.coveredSequence,
|
|
94
|
+
},
|
|
95
|
+
});
|
|
96
|
+
return Object.freeze({
|
|
97
|
+
internalInferenceId: result.internalInferenceId,
|
|
98
|
+
rootInternalInferenceId: context.attempt.rootId,
|
|
99
|
+
internalSessionId: result.internalSessionId,
|
|
100
|
+
purpose: context.attempt.purpose,
|
|
101
|
+
artifactId: checkpoint.checkpointId,
|
|
102
|
+
completedAt: new Date().toISOString(),
|
|
103
|
+
metadata: JSON.stringify({ coveredSequence: checkpoint.coveredSequence }),
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
classifyError(error: unknown) {
|
|
108
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
109
|
+
if (message.includes("source changed") || message.includes("coverage") || message.includes("source range")) {
|
|
110
|
+
return { kind: "terminal" as const, code: "checkpoint_source_conflict" };
|
|
111
|
+
}
|
|
112
|
+
if (message.includes("empty summary") || message.includes("no records")) {
|
|
113
|
+
return { kind: "terminal" as const, code: "invalid_checkpoint_result" };
|
|
114
|
+
}
|
|
115
|
+
return { kind: "retryable" as const, code: "checkpoint_inference_failed" };
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function readRecords(
|
|
120
|
+
repository: Parameters<InternalInferenceStrategy["prepare"]>[0]["persistence"]["records"],
|
|
121
|
+
conversationId: Parameters<typeof repository.list>[0],
|
|
122
|
+
afterSequence: number,
|
|
123
|
+
throughSequence: number,
|
|
124
|
+
): Promise<readonly ConversationRecord[]> {
|
|
125
|
+
const records: ConversationRecord[] = [];
|
|
126
|
+
let cursor: string | undefined;
|
|
127
|
+
do {
|
|
128
|
+
const page = await repository.list(conversationId, {
|
|
129
|
+
afterSequence,
|
|
130
|
+
throughSequence,
|
|
131
|
+
kinds: ["message"],
|
|
132
|
+
limit: 1_000,
|
|
133
|
+
...(cursor ? { cursor } : {}),
|
|
134
|
+
});
|
|
135
|
+
records.push(...page.records);
|
|
136
|
+
cursor = page.nextCursor;
|
|
137
|
+
} while (cursor);
|
|
138
|
+
return Object.freeze(records);
|
|
139
|
+
}
|