@qlairoslabs/acp-client 0.10.2 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONSUMER_GUIDE.md +177 -5
- package/package.json +1 -1
- package/src/agent/adoption/checkpoint-floor.ts +47 -0
- package/src/agent/adoption/config.ts +57 -0
- package/src/agent/adoption/index.ts +10 -0
- package/src/agent/adoption/provider-session-delete.ts +27 -0
- package/src/agent/adoption/provider-sessions.ts +73 -0
- package/src/agent/adoption/recap.ts +15 -0
- package/src/agent/adoption/replay.ts +98 -0
- package/src/agent/config.ts +182 -0
- package/src/agent/conversation-manager.ts +1048 -0
- package/src/agent/manager-settings.ts +46 -0
- package/src/agent/persisted-lifecycle.ts +309 -0
- package/src/agent/persistence-policy/index.ts +8 -0
- package/src/agent/persistence-policy/resolver.ts +118 -0
- package/src/agent/persistence-policy/types.ts +50 -0
- package/src/agent/record-capture.ts +243 -0
- package/src/agent-conversation-contracts.ts +2 -0
- package/src/agent-conversation-errors.ts +24 -0
- package/src/agent-conversation-owner.ts +2 -0
- package/src/agent-session.ts +117 -3
- package/src/agent.ts +63 -1233
- package/src/audit/config.ts +29 -0
- package/src/audit/index.ts +1 -0
- package/src/checkpointing/contracts.ts +30 -3
- package/src/checkpointing/persistence/sqlite-repository.ts +49 -8
- package/src/checkpointing/recovery.ts +4 -2
- package/src/checkpointing/strategy.ts +36 -7
- package/src/client.ts +22 -1
- package/src/controller.ts +3 -0
- package/src/identity/checkpoint-backed.ts +2 -2
- package/src/index.ts +14 -0
- package/src/internal-inference/contracts.ts +23 -0
- package/src/internal-inference/coordination/manager.ts +22 -8
- package/src/persistence/backend.ts +17 -0
- package/src/persistence/sqlite-backend.ts +30 -4
- package/src/persistence/sqlite-provider-sessions.ts +35 -0
- package/src/persistence/sqlite-schema.ts +74 -7
- package/src/transport/acp-transport.ts +3 -0
package/src/audit/config.ts
CHANGED
|
@@ -188,3 +188,32 @@ function safeInteger(value: number, minimum: number, label: string): number {
|
|
|
188
188
|
}
|
|
189
189
|
return value;
|
|
190
190
|
}
|
|
191
|
+
|
|
192
|
+
/** Audit kinds observed at agent scope. A conversation cannot tune them: they are not about one conversation. */
|
|
193
|
+
const AGENT_SCOPE_AUDIT_KINDS = new Set(["agent_lifecycle", "identity", "internal_inference"]);
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* The audit configuration one conversation runs with: the Agent's destination and delivery settings
|
|
197
|
+
* unchanged, with its capture layered over by the conversation's override (keys the override sets replace
|
|
198
|
+
* the Agent's; omitted keys follow the Agent). The result carries its own fingerprint, so an entry says which
|
|
199
|
+
* policy projected it. An override that changes nothing returns the Agent's configuration itself.
|
|
200
|
+
*/
|
|
201
|
+
export function resolveConversationAuditConfig(
|
|
202
|
+
base: ResolvedAgentAuditLogConfig,
|
|
203
|
+
baseCapture: AgentAuditCaptureConfig | undefined,
|
|
204
|
+
override: AgentAuditCaptureConfig,
|
|
205
|
+
): ResolvedAgentAuditLogConfig {
|
|
206
|
+
for (const key of Object.keys(override)) {
|
|
207
|
+
if (AGENT_SCOPE_AUDIT_KINDS.has(key)) {
|
|
208
|
+
throw new Error(`conversation audit capture cannot select agent-scope kind: ${key}`);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
const capture = resolveAgentAuditCapture({ ...baseCapture, ...override });
|
|
212
|
+
const captureFingerprint = sha256CanonicalJson({
|
|
213
|
+
projectionSchemaVersion: 1,
|
|
214
|
+
capture,
|
|
215
|
+
limits: DEFAULT_PERSISTENCE_LIMITS,
|
|
216
|
+
});
|
|
217
|
+
if (captureFingerprint === base.captureFingerprint) return base;
|
|
218
|
+
return Object.freeze({ ...base, capture, captureFingerprint });
|
|
219
|
+
}
|
package/src/audit/index.ts
CHANGED
|
@@ -3,14 +3,33 @@ import type { InternalInferenceId } from "../internal-inference/contracts.ts";
|
|
|
3
3
|
|
|
4
4
|
export type ConversationRecoveryCheckpointId = `chk-${string}`;
|
|
5
5
|
|
|
6
|
+
/**
|
|
7
|
+
* What made a checkpoint. `internal_inference` is the normal case: a model call over stored records.
|
|
8
|
+
* The adoption sources have no generator: the summary is the recap the adopted session wrote of its own
|
|
9
|
+
* history (`adoption_recap`), or empty (`adoption_baseline`, a floor only). Either way the checkpoint says
|
|
10
|
+
* where summarizing starts, so nothing ever tries to summarize the history that came before it.
|
|
11
|
+
*/
|
|
12
|
+
export type ConversationRecoveryCheckpointSource =
|
|
13
|
+
| "internal_inference"
|
|
14
|
+
| "adoption_recap"
|
|
15
|
+
| "adoption_baseline";
|
|
16
|
+
|
|
6
17
|
export interface ConversationRecoveryCheckpoint {
|
|
7
18
|
readonly checkpointId: ConversationRecoveryCheckpointId;
|
|
8
19
|
readonly agentConversationId: AgentConversationId;
|
|
9
20
|
readonly revision: number;
|
|
10
21
|
readonly coveredSequence: number;
|
|
11
22
|
readonly previousCheckpointId?: ConversationRecoveryCheckpointId;
|
|
12
|
-
|
|
23
|
+
/** Absent for the adoption sources, which no internal inference generated. */
|
|
24
|
+
readonly generatorInternalInferenceId?: InternalInferenceId;
|
|
25
|
+
readonly source: ConversationRecoveryCheckpointSource;
|
|
26
|
+
/** Empty only for `adoption_baseline`. */
|
|
13
27
|
readonly summary: string;
|
|
28
|
+
/**
|
|
29
|
+
* Adoption only: the checkpoint schedule counts successful responses after this sequence, so the history
|
|
30
|
+
* an adoption imported does not use up the milestones a new conversation starts with.
|
|
31
|
+
*/
|
|
32
|
+
readonly responsesCountedAfterSequence?: number;
|
|
14
33
|
readonly createdAt: string;
|
|
15
34
|
readonly metadata?: string;
|
|
16
35
|
}
|
|
@@ -20,8 +39,11 @@ export interface PublishConversationRecoveryCheckpointInput {
|
|
|
20
39
|
readonly agentConversationId: AgentConversationId;
|
|
21
40
|
readonly coveredSequence: number;
|
|
22
41
|
readonly previousCheckpointId?: ConversationRecoveryCheckpointId;
|
|
23
|
-
readonly generatorInternalInferenceId
|
|
42
|
+
readonly generatorInternalInferenceId?: InternalInferenceId;
|
|
43
|
+
/** Default `internal_inference`, which requires a generator and a summary. */
|
|
44
|
+
readonly source?: ConversationRecoveryCheckpointSource;
|
|
24
45
|
readonly summary: string;
|
|
46
|
+
readonly responsesCountedAfterSequence?: number;
|
|
25
47
|
readonly createdAt?: string;
|
|
26
48
|
readonly metadata?: string;
|
|
27
49
|
}
|
|
@@ -32,7 +54,10 @@ export interface ConversationRecoveryCheckpointListOptions {
|
|
|
32
54
|
}
|
|
33
55
|
|
|
34
56
|
export interface ConversationRecoveryCheckpointRepository {
|
|
35
|
-
/**
|
|
57
|
+
/**
|
|
58
|
+
* Count completed provider turns using the stable operation ID on assistant messages, after the
|
|
59
|
+
* adoption checkpoint's `responsesCountedAfterSequence` when the conversation has one.
|
|
60
|
+
*/
|
|
36
61
|
successfulResponseCount(agentConversationId: AgentConversationId): Promise<number>;
|
|
37
62
|
latestMessageSequence(agentConversationId: AgentConversationId): Promise<number>;
|
|
38
63
|
latest(agentConversationId: AgentConversationId): Promise<ConversationRecoveryCheckpoint | null>;
|
|
@@ -42,4 +67,6 @@ export interface ConversationRecoveryCheckpointRepository {
|
|
|
42
67
|
options?: ConversationRecoveryCheckpointListOptions,
|
|
43
68
|
): Promise<readonly ConversationRecoveryCheckpoint[]>;
|
|
44
69
|
publish(input: PublishConversationRecoveryCheckpointInput): Promise<ConversationRecoveryCheckpoint>;
|
|
70
|
+
/** Delete every checkpoint of a conversation. Returns how many. Optional. */
|
|
71
|
+
deleteForConversation?(agentConversationId: AgentConversationId): Promise<number>;
|
|
45
72
|
}
|
|
@@ -7,6 +7,7 @@ import type {
|
|
|
7
7
|
ConversationRecoveryCheckpointId,
|
|
8
8
|
ConversationRecoveryCheckpointListOptions,
|
|
9
9
|
ConversationRecoveryCheckpointRepository,
|
|
10
|
+
ConversationRecoveryCheckpointSource,
|
|
10
11
|
PublishConversationRecoveryCheckpointInput,
|
|
11
12
|
} from "../contracts.ts";
|
|
12
13
|
|
|
@@ -18,8 +19,10 @@ interface CheckpointRow {
|
|
|
18
19
|
revision: number;
|
|
19
20
|
covered_sequence: number;
|
|
20
21
|
previous_checkpoint_id: string | null;
|
|
21
|
-
generator_internal_inference_id: string;
|
|
22
|
+
generator_internal_inference_id: string | null;
|
|
23
|
+
source: string;
|
|
22
24
|
summary: string;
|
|
25
|
+
responses_counted_after_sequence: number | null;
|
|
23
26
|
created_at: string;
|
|
24
27
|
metadata: string | null;
|
|
25
28
|
}
|
|
@@ -36,7 +39,12 @@ implements ConversationRecoveryCheckpointRepository {
|
|
|
36
39
|
WHERE r.agent_conversation_id = ? AND r.kind = 'message'
|
|
37
40
|
AND m.role = 'assistant'
|
|
38
41
|
AND m.status = 'completed'
|
|
39
|
-
AND r.operation_id IS NOT NULL
|
|
42
|
+
AND r.operation_id IS NOT NULL
|
|
43
|
+
AND r.sequence > COALESCE((
|
|
44
|
+
SELECT c.responses_counted_after_sequence FROM conversation_recovery_checkpoints c
|
|
45
|
+
WHERE c.agent_conversation_id = r.agent_conversation_id AND c.source <> 'internal_inference'
|
|
46
|
+
ORDER BY c.revision LIMIT 1
|
|
47
|
+
), 0)`,
|
|
40
48
|
).get(agentConversationId);
|
|
41
49
|
return Number(row?.count ?? 0);
|
|
42
50
|
}
|
|
@@ -49,6 +57,19 @@ implements ConversationRecoveryCheckpointRepository {
|
|
|
49
57
|
return Number(row?.sequence ?? 0);
|
|
50
58
|
}
|
|
51
59
|
|
|
60
|
+
async deleteForConversation(agentConversationId: AgentConversationId): Promise<number> {
|
|
61
|
+
return await this.runWrite(() => {
|
|
62
|
+
const count = this.database.query<{ n: number }, [string]>(
|
|
63
|
+
"SELECT COUNT(*) AS n FROM conversation_recovery_checkpoints WHERE agent_conversation_id = ?",
|
|
64
|
+
).get(agentConversationId)?.n ?? 0;
|
|
65
|
+
// One statement: the checkpoints reference each other (previous_checkpoint_id), and a single DELETE
|
|
66
|
+
// checks that reference after all of them are gone.
|
|
67
|
+
this.database.query("DELETE FROM conversation_recovery_checkpoints WHERE agent_conversation_id = ?")
|
|
68
|
+
.run(agentConversationId);
|
|
69
|
+
return Number(count);
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
52
73
|
async latest(agentConversationId: AgentConversationId): Promise<ConversationRecoveryCheckpoint | null> {
|
|
53
74
|
const row = this.database.query<CheckpointRow, [string]>(
|
|
54
75
|
`SELECT * FROM conversation_recovery_checkpoints
|
|
@@ -84,7 +105,17 @@ implements ConversationRecoveryCheckpointRepository {
|
|
|
84
105
|
async publish(input: PublishConversationRecoveryCheckpointInput): Promise<ConversationRecoveryCheckpoint> {
|
|
85
106
|
return await this.runWrite(() => {
|
|
86
107
|
const summary = input.summary.trim();
|
|
87
|
-
|
|
108
|
+
const source = input.source ?? "internal_inference";
|
|
109
|
+
// Only a baseline is a floor with nothing to say; every other checkpoint summarizes something, and
|
|
110
|
+
// only an internal inference has a generator.
|
|
111
|
+
if (source === "adoption_baseline" ? summary !== "" : !summary) {
|
|
112
|
+
throw new Error(source === "adoption_baseline"
|
|
113
|
+
? "an adoption baseline checkpoint has no summary"
|
|
114
|
+
: "recovery checkpoint summary cannot be blank");
|
|
115
|
+
}
|
|
116
|
+
if ((source === "internal_inference") !== (input.generatorInternalInferenceId !== undefined)) {
|
|
117
|
+
throw new Error("only an internal-inference checkpoint has a generator, and it must have one");
|
|
118
|
+
}
|
|
88
119
|
if (!Number.isSafeInteger(input.coveredSequence) || input.coveredSequence < 1) {
|
|
89
120
|
throw new Error("recovery checkpoint coveredSequence must be a positive integer");
|
|
90
121
|
}
|
|
@@ -97,6 +128,7 @@ implements ConversationRecoveryCheckpointRepository {
|
|
|
97
128
|
checkpoint.agentConversationId !== input.agentConversationId
|
|
98
129
|
|| checkpoint.coveredSequence !== input.coveredSequence
|
|
99
130
|
|| checkpoint.generatorInternalInferenceId !== input.generatorInternalInferenceId
|
|
131
|
+
|| checkpoint.source !== source
|
|
100
132
|
|| checkpoint.summary !== summary
|
|
101
133
|
) throw new PersistenceConflictError(`recovery checkpoint id conflict: ${input.checkpointId}`);
|
|
102
134
|
return checkpoint;
|
|
@@ -117,20 +149,23 @@ implements ConversationRecoveryCheckpointRepository {
|
|
|
117
149
|
this.database.query(
|
|
118
150
|
`INSERT INTO conversation_recovery_checkpoints(
|
|
119
151
|
checkpoint_id, agent_conversation_id, revision, covered_sequence,
|
|
120
|
-
previous_checkpoint_id, generator_internal_inference_id,
|
|
121
|
-
|
|
152
|
+
previous_checkpoint_id, generator_internal_inference_id, source, summary,
|
|
153
|
+
responses_counted_after_sequence, created_at, metadata
|
|
154
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
122
155
|
).run(
|
|
123
156
|
input.checkpointId,
|
|
124
157
|
input.agentConversationId,
|
|
125
158
|
revision,
|
|
126
159
|
input.coveredSequence,
|
|
127
160
|
input.previousCheckpointId ?? null,
|
|
128
|
-
input.generatorInternalInferenceId,
|
|
161
|
+
input.generatorInternalInferenceId ?? null,
|
|
162
|
+
source,
|
|
129
163
|
summary,
|
|
164
|
+
input.responsesCountedAfterSequence ?? null,
|
|
130
165
|
createdAt,
|
|
131
166
|
input.metadata ?? null,
|
|
132
167
|
);
|
|
133
|
-
return Object.freeze({ ...input, summary, revision, createdAt });
|
|
168
|
+
return Object.freeze({ ...input, source, summary, revision, createdAt });
|
|
134
169
|
});
|
|
135
170
|
}
|
|
136
171
|
}
|
|
@@ -144,8 +179,14 @@ function fromRow(row: CheckpointRow): ConversationRecoveryCheckpoint {
|
|
|
144
179
|
...(row.previous_checkpoint_id
|
|
145
180
|
? { previousCheckpointId: row.previous_checkpoint_id as ConversationRecoveryCheckpointId }
|
|
146
181
|
: {}),
|
|
147
|
-
|
|
182
|
+
...(row.generator_internal_inference_id
|
|
183
|
+
? { generatorInternalInferenceId: row.generator_internal_inference_id as InternalInferenceId }
|
|
184
|
+
: {}),
|
|
185
|
+
source: row.source as ConversationRecoveryCheckpointSource,
|
|
148
186
|
summary: row.summary,
|
|
187
|
+
...(row.responses_counted_after_sequence !== null
|
|
188
|
+
? { responsesCountedAfterSequence: Number(row.responses_counted_after_sequence) }
|
|
189
|
+
: {}),
|
|
149
190
|
createdAt: row.created_at,
|
|
150
191
|
...(row.metadata ? { metadata: row.metadata } : {}),
|
|
151
192
|
});
|
|
@@ -90,8 +90,10 @@ export async function buildRecoverySeed(
|
|
|
90
90
|
return Object.freeze({
|
|
91
91
|
prompt: [
|
|
92
92
|
config.seedInstruction,
|
|
93
|
-
|
|
94
|
-
checkpoint.summary
|
|
93
|
+
// An adoption baseline has no summary: only the messages after it are known.
|
|
94
|
+
...(checkpoint.summary
|
|
95
|
+
? [`Continuation checkpoint through canonical sequence ${checkpoint.coveredSequence}:`, checkpoint.summary]
|
|
96
|
+
: []),
|
|
95
97
|
tail.length
|
|
96
98
|
? `Canonical messages after the checkpoint:\n${JSON.stringify(tail)}`
|
|
97
99
|
: "There are no canonical messages after the checkpoint.",
|
|
@@ -13,6 +13,20 @@ const CHECKPOINT_READ_ONLY_INSTRUCTION = [
|
|
|
13
13
|
"Only summarize the records supplied in this prompt.",
|
|
14
14
|
].join(" ");
|
|
15
15
|
|
|
16
|
+
/**
|
|
17
|
+
* The most characters of stored records one checkpoint prompt may carry. Harnesses refuse a message past
|
|
18
|
+
* about a million characters (Codex: "Message exceeds the maximum length of 1048576 characters"), and a
|
|
19
|
+
* prompt that cannot be sent cannot succeed however often it is retried.
|
|
20
|
+
*/
|
|
21
|
+
export const MAX_CHECKPOINT_SOURCE_CHARS = 700_000;
|
|
22
|
+
|
|
23
|
+
export class CheckpointSourceTooLargeError extends Error {
|
|
24
|
+
constructor(readonly chars: number, readonly limit: number) {
|
|
25
|
+
super(`conversation checkpoint source is too large: ${chars} characters, the limit is ${limit}`);
|
|
26
|
+
this.name = "CheckpointSourceTooLargeError";
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
16
30
|
export type ConversationCheckpointPayload = {
|
|
17
31
|
readonly instruction: string;
|
|
18
32
|
};
|
|
@@ -47,15 +61,20 @@ implements InternalInferenceStrategy<ConversationCheckpointPayload> {
|
|
|
47
61
|
if (through <= from) throw new Error("conversation checkpoint source range is empty");
|
|
48
62
|
const records = await readRecords(context.persistence.records, conversationId, from, through);
|
|
49
63
|
if (!records.length) throw new Error("conversation checkpoint source contains no records");
|
|
64
|
+
const serialized = JSON.stringify(records);
|
|
65
|
+
if (serialized.length + (previous?.summary.length ?? 0) > MAX_CHECKPOINT_SOURCE_CHARS) {
|
|
66
|
+
throw new CheckpointSourceTooLargeError(serialized.length + (previous?.summary.length ?? 0), MAX_CHECKPOINT_SOURCE_CHARS);
|
|
67
|
+
}
|
|
50
68
|
return Object.freeze({
|
|
51
69
|
prompt: [
|
|
52
70
|
payload.instruction,
|
|
53
71
|
CHECKPOINT_READ_ONLY_INSTRUCTION,
|
|
54
|
-
|
|
72
|
+
// An adoption baseline is a floor without a summary: nothing to build on, and nothing before it is read.
|
|
73
|
+
previous?.summary
|
|
55
74
|
? `Previous continuation summary:\n${previous.summary}`
|
|
56
75
|
: "There is no previous continuation summary.",
|
|
57
76
|
`New canonical records after sequence ${from} through ${through}:`,
|
|
58
|
-
|
|
77
|
+
serialized,
|
|
59
78
|
].join("\n\n"),
|
|
60
79
|
metadata: JSON.stringify({ previousCheckpointId: previous?.checkpointId ?? null, through }),
|
|
61
80
|
});
|
|
@@ -77,25 +96,32 @@ implements InternalInferenceStrategy<ConversationCheckpointPayload> {
|
|
|
77
96
|
? { previousCheckpointId: context.attempt.sourceCheckpointId as `chk-${string}` }
|
|
78
97
|
: {}),
|
|
79
98
|
generatorInternalInferenceId: result.internalInferenceId,
|
|
99
|
+
source: "internal_inference",
|
|
80
100
|
summary,
|
|
81
101
|
});
|
|
82
|
-
const
|
|
102
|
+
const record = {
|
|
83
103
|
recordId: `${result.internalInferenceId}:checkpoint`,
|
|
84
104
|
agentSessionId: context.attempt.agentSessionId,
|
|
85
105
|
agentConversationId: conversationId,
|
|
86
|
-
kind: "native_action",
|
|
106
|
+
kind: "native_action" as const,
|
|
87
107
|
timestamp: checkpoint.createdAt,
|
|
88
108
|
action: "conversation_checkpoint",
|
|
89
|
-
state: "completed",
|
|
109
|
+
state: "completed" as const,
|
|
90
110
|
output: {
|
|
91
111
|
internalInferenceId: result.internalInferenceId,
|
|
92
112
|
checkpointId: checkpoint.checkpointId,
|
|
93
113
|
coveredSequence: checkpoint.coveredSequence,
|
|
94
114
|
},
|
|
95
|
-
}
|
|
115
|
+
};
|
|
116
|
+
// Under the conversation's capture and audit policy when the Agent supplies one: the record is stored at
|
|
117
|
+
// the conversation's `native_action` level (or dropped) and audited as the conversation says. Without
|
|
118
|
+
// one it is appended as it always was.
|
|
119
|
+
const appended = context.appendRecord
|
|
120
|
+
? await context.appendRecord(record)
|
|
121
|
+
: await context.persistence.records.append(record);
|
|
96
122
|
// Hand the committed record to the manager so it reaches the Agent's live bus after
|
|
97
123
|
// the completion transaction commits, exactly like every other Agent-owned record.
|
|
98
|
-
context.onRecordAppended?.(appended);
|
|
124
|
+
if (appended) context.onRecordAppended?.(appended);
|
|
99
125
|
return Object.freeze({
|
|
100
126
|
internalInferenceId: result.internalInferenceId,
|
|
101
127
|
rootInternalInferenceId: context.attempt.rootId,
|
|
@@ -108,6 +134,9 @@ implements InternalInferenceStrategy<ConversationCheckpointPayload> {
|
|
|
108
134
|
}
|
|
109
135
|
|
|
110
136
|
classifyError(error: unknown) {
|
|
137
|
+
if (error instanceof CheckpointSourceTooLargeError) {
|
|
138
|
+
return { kind: "terminal" as const, code: "checkpoint_source_too_large" };
|
|
139
|
+
}
|
|
111
140
|
const message = error instanceof Error ? error.message : String(error);
|
|
112
141
|
if (message.includes("source changed") || message.includes("coverage") || message.includes("source range")) {
|
|
113
142
|
return { kind: "terminal" as const, code: "checkpoint_source_conflict" };
|
package/src/client.ts
CHANGED
|
@@ -134,6 +134,11 @@ export interface StartSessionOptions {
|
|
|
134
134
|
loadFailure?: SessionLoadFailure;
|
|
135
135
|
/** MCP servers bound at session creation. */
|
|
136
136
|
mcpServers?: schema.McpServer[];
|
|
137
|
+
/**
|
|
138
|
+
* Raw `session/update` notifications of the history a loaded session replays. Without it the replay is
|
|
139
|
+
* dropped: it arrives before the load returns and belongs to no turn.
|
|
140
|
+
*/
|
|
141
|
+
onReplayUpdate?: (notification: unknown) => void;
|
|
137
142
|
}
|
|
138
143
|
|
|
139
144
|
export type SessionLoadFailure = "error" | "new";
|
|
@@ -401,7 +406,10 @@ export class AcpClient implements AgentClient {
|
|
|
401
406
|
|
|
402
407
|
if (resumeId && this.capabilities.agent.loadSession) {
|
|
403
408
|
try {
|
|
404
|
-
const result = await this.loadSessionInternal(transport, resumeId, {
|
|
409
|
+
const result = await this.loadSessionInternal(transport, resumeId, {
|
|
410
|
+
mcpServers,
|
|
411
|
+
...(options.onReplayUpdate ? { onUpdate: options.onReplayUpdate } : {}),
|
|
412
|
+
});
|
|
405
413
|
sessionId = result.sessionId;
|
|
406
414
|
resumed = result.resumed;
|
|
407
415
|
} catch (err) {
|
|
@@ -499,6 +507,19 @@ export class AcpClient implements AgentClient {
|
|
|
499
507
|
return { sessionId, resumed: true };
|
|
500
508
|
}
|
|
501
509
|
|
|
510
|
+
/**
|
|
511
|
+
* Ask the agent to delete a session it holds (`session/delete`), when advertised. This is the provider's own
|
|
512
|
+
* deletion: it does not touch any local record, and not every provider offers it.
|
|
513
|
+
*/
|
|
514
|
+
async deleteSession(sessionId: string): Promise<void> {
|
|
515
|
+
const transport = this.requireTransport();
|
|
516
|
+
if (!this.capabilities.agent.sessionCapabilities.delete) {
|
|
517
|
+
throw new Error("agent does not advertise session/delete (sessionCapabilities.delete)");
|
|
518
|
+
}
|
|
519
|
+
await transport.deleteSession({ sessionId } as schema.DeleteSessionRequest);
|
|
520
|
+
this.log.info("session_deleted", { sessionId });
|
|
521
|
+
}
|
|
522
|
+
|
|
502
523
|
/** Fork an existing session and switch this client to the newly-created fork. */
|
|
503
524
|
async forkSession(
|
|
504
525
|
sessionId: string,
|
package/src/controller.ts
CHANGED
|
@@ -51,6 +51,8 @@ export interface AgentControllerConfig {
|
|
|
51
51
|
sessionId?: string;
|
|
52
52
|
/** Policy when sessionId cannot be loaded. Default "new" for compatibility. */
|
|
53
53
|
sessionLoadFailure?: SessionLoadFailure;
|
|
54
|
+
/** Receives the history a loaded `sessionId` replays (raw `session/update` notifications). */
|
|
55
|
+
onSessionReplay?: (notification: unknown) => void;
|
|
54
56
|
/** Default MCP servers bound at session creation/switch, unless a call overrides them. */
|
|
55
57
|
mcpServers?: schema.McpServer[];
|
|
56
58
|
defaultPermission?: "approve" | "cancel";
|
|
@@ -508,6 +510,7 @@ export class AgentController implements AgentClient {
|
|
|
508
510
|
result = await client.startSession({
|
|
509
511
|
mcpServers: this.config.mcpServers,
|
|
510
512
|
loadFailure: this.config.sessionLoadFailure,
|
|
513
|
+
...(this.config.onSessionReplay ? { onReplayUpdate: this.config.onSessionReplay } : {}),
|
|
511
514
|
});
|
|
512
515
|
} catch (err) {
|
|
513
516
|
if (sessionId && this.config.sessionLoadFailure === "error") {
|
|
@@ -160,7 +160,7 @@ export class CheckpointBackedIdentityRuntime implements AgentIdentityRuntime {
|
|
|
160
160
|
const header = `Source conversation ${conversation.agentConversationId}${label}; participants=${JSON.stringify(participants)}\n`;
|
|
161
161
|
if (header.length >= maxChars) return null;
|
|
162
162
|
const start = cursor?.deliveredThroughSequence ?? 0;
|
|
163
|
-
const initialSummary = !cursor && checkpoint
|
|
163
|
+
const initialSummary = !cursor && checkpoint?.summary
|
|
164
164
|
? summaryText(checkpoint, "Summary")
|
|
165
165
|
: "";
|
|
166
166
|
const summaryFits = initialSummary.length > 0 && header.length + initialSummary.length <= maxChars;
|
|
@@ -173,7 +173,7 @@ export class CheckpointBackedIdentityRuntime implements AgentIdentityRuntime {
|
|
|
173
173
|
);
|
|
174
174
|
let text = header + (summaryFits ? initialSummary : "") + raw.text;
|
|
175
175
|
let throughSequence = Math.max(from, raw.throughSequence);
|
|
176
|
-
if (cursor && !raw.complete && checkpoint && checkpoint.coveredSequence > throughSequence) {
|
|
176
|
+
if (cursor && !raw.complete && checkpoint?.summary && checkpoint.coveredSequence > throughSequence) {
|
|
177
177
|
const replacement = summaryText(checkpoint, "Updated summary, superseding earlier source context");
|
|
178
178
|
if (header.length + replacement.length <= maxChars) {
|
|
179
179
|
const tail = await this.readMessages(
|
package/src/index.ts
CHANGED
|
@@ -44,6 +44,18 @@ export type {
|
|
|
44
44
|
CreateAgentConversationConfig,
|
|
45
45
|
OpenAgentConversationConfig,
|
|
46
46
|
OpenOwnedAgentConversationResult,
|
|
47
|
+
AdoptProviderSessionConfig,
|
|
48
|
+
ClearTranscriptOptions,
|
|
49
|
+
ClearTranscriptResult,
|
|
50
|
+
DeleteConversationOptions,
|
|
51
|
+
DeleteConversationResult,
|
|
52
|
+
ListProviderSessionsOptions,
|
|
53
|
+
ProviderSessionSummary,
|
|
54
|
+
AgentConversationAuditCaptureConfig,
|
|
55
|
+
AgentConversationPersistenceOverride,
|
|
56
|
+
AgentScopeAuditObservationKind,
|
|
57
|
+
ConversationPersistenceContext,
|
|
58
|
+
ConversationPersistenceResolver,
|
|
47
59
|
} from "./agent.ts";
|
|
48
60
|
export {
|
|
49
61
|
OUT_OF_BAND_MESSAGE_ORIGIN,
|
|
@@ -180,6 +192,8 @@ export {
|
|
|
180
192
|
ContinuationUnavailableError,
|
|
181
193
|
DirectAuditPersistenceUnsupportedError,
|
|
182
194
|
ProviderSessionError,
|
|
195
|
+
ProviderSessionInUseError,
|
|
196
|
+
ProviderSessionListUnsupportedError,
|
|
183
197
|
} from "./agent-session.ts";
|
|
184
198
|
export type { ProviderSessionErrorDetails } from "./agent-session.ts";
|
|
185
199
|
export type {
|
|
@@ -4,6 +4,8 @@ import type { OperationMeteringRecord, OperationOutcome } from "../metering/reco
|
|
|
4
4
|
import type { StatefulSubscribable, Subscribable } from "../observation/contracts.ts";
|
|
5
5
|
import type {
|
|
6
6
|
ConversationRecord,
|
|
7
|
+
MeteringRecordRetention,
|
|
8
|
+
NewConversationRecord,
|
|
7
9
|
PersistenceJsonValue,
|
|
8
10
|
PersistenceScope,
|
|
9
11
|
} from "../persistence/backend.ts";
|
|
@@ -201,6 +203,21 @@ export interface InternalInferencePreparationContext {
|
|
|
201
203
|
readonly signal?: AbortSignal;
|
|
202
204
|
}
|
|
203
205
|
|
|
206
|
+
/**
|
|
207
|
+
* What one conversation persists, for the writes an internal inference makes about it. Resolved before the
|
|
208
|
+
* inference runs, so a policy that cannot be resolved fails the attempt instead of writing under defaults.
|
|
209
|
+
*/
|
|
210
|
+
export interface ConversationWritePolicy {
|
|
211
|
+
/** Retention of the detailed metering record of this conversation's inferences. */
|
|
212
|
+
readonly meteringRecords: MeteringRecordRetention;
|
|
213
|
+
/**
|
|
214
|
+
* Append a canonical record as the conversation's capture and audit policy say: it is stored at its capture
|
|
215
|
+
* level (or dropped, when the level is `none`) and its audit entry is queued, in the given transaction.
|
|
216
|
+
* Returns the stored record, or `undefined` when capture dropped it.
|
|
217
|
+
*/
|
|
218
|
+
appendRecord(persistence: PersistenceScope, record: NewConversationRecord): Promise<ConversationRecord | undefined>;
|
|
219
|
+
}
|
|
220
|
+
|
|
204
221
|
export interface InternalInferenceCompletionContext {
|
|
205
222
|
readonly attempt: InternalInferenceSnapshot;
|
|
206
223
|
/** Transaction-scoped persistence used to publish the purpose artifact atomically. */
|
|
@@ -213,6 +230,12 @@ export interface InternalInferenceCompletionContext {
|
|
|
213
230
|
* simply do not call it.
|
|
214
231
|
*/
|
|
215
232
|
readonly onRecordAppended?: (record: ConversationRecord) => void;
|
|
233
|
+
/**
|
|
234
|
+
* Append a canonical record about the attempt's conversation under that conversation's capture and audit
|
|
235
|
+
* policy, inside this completion transaction. Absent when the Agent has no per-conversation policy to
|
|
236
|
+
* apply, in which case a strategy appends through `persistence.records` as before.
|
|
237
|
+
*/
|
|
238
|
+
readonly appendRecord?: (record: NewConversationRecord) => Promise<ConversationRecord | undefined>;
|
|
216
239
|
}
|
|
217
240
|
|
|
218
241
|
export interface InternalInferenceStrategy<TPayload = PersistenceJsonValue> {
|
|
@@ -42,6 +42,13 @@ export interface DefaultInternalInferenceManagerConfig {
|
|
|
42
42
|
session: { readonly internalSessionId: string; readonly model: string | null },
|
|
43
43
|
) => Promise<InternalInferenceMeteringOperation | null>;
|
|
44
44
|
readonly meteringRecords?: import("../../persistence/backend.ts").MeteringRecordRetention;
|
|
45
|
+
/**
|
|
46
|
+
* What a conversation persists, asked for before an attempt about that conversation runs. A failure here
|
|
47
|
+
* fails the attempt through the normal retry rules; nothing is written under the Agent's defaults.
|
|
48
|
+
*/
|
|
49
|
+
readonly resolveConversationWrites?: (
|
|
50
|
+
agentConversationId: NonNullable<InternalInferenceSnapshot["agentConversationId"]>,
|
|
51
|
+
) => Promise<import("../contracts.ts").ConversationWritePolicy>;
|
|
45
52
|
readonly pollIntervalMs?: number;
|
|
46
53
|
/**
|
|
47
54
|
* Observe canonical records appended by a strategy's completion, after the transaction
|
|
@@ -225,6 +232,7 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
|
|
|
225
232
|
): Promise<void> {
|
|
226
233
|
let metering: InternalInferenceMeteringOperation | null = null;
|
|
227
234
|
let meteringRecord: OperationMeteringRecord | null = null;
|
|
235
|
+
let writes: import("../contracts.ts").ConversationWritePolicy | undefined;
|
|
228
236
|
const heartbeat = setInterval(() => {
|
|
229
237
|
void this.config.repository.heartbeat(
|
|
230
238
|
attempt.internalInferenceId,
|
|
@@ -240,6 +248,9 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
|
|
|
240
248
|
attempt.input.version,
|
|
241
249
|
);
|
|
242
250
|
this.publishProgress(attempt.internalInferenceId, "preparing_input");
|
|
251
|
+
if (attempt.agentConversationId && this.config.resolveConversationWrites) {
|
|
252
|
+
writes = await this.config.resolveConversationWrites(attempt.agentConversationId);
|
|
253
|
+
}
|
|
243
254
|
const payload = strategy.validatePayload(attempt.input.payload);
|
|
244
255
|
const prepared = await strategy.prepare({
|
|
245
256
|
attempt: snapshotOf(attempt),
|
|
@@ -289,6 +300,7 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
|
|
|
289
300
|
attempt: snapshotOf(attempt),
|
|
290
301
|
persistence,
|
|
291
302
|
onRecordAppended: (record) => appended.push(record),
|
|
303
|
+
...(writes ? { appendRecord: (record) => writes!.appendRecord(persistence, record) } : {}),
|
|
292
304
|
}, result);
|
|
293
305
|
if (this.fenced.has(attempt.internalInferenceId)) {
|
|
294
306
|
throw new Error("internal inference was fenced during completion");
|
|
@@ -297,13 +309,13 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
|
|
|
297
309
|
await persistence.metering.commit({
|
|
298
310
|
agentConversationId: attempt.agentConversationId,
|
|
299
311
|
record: meteringRecord,
|
|
300
|
-
meteringRecords: this.config.meteringRecords ?? "all",
|
|
312
|
+
meteringRecords: writes?.meteringRecords ?? this.config.meteringRecords ?? "all",
|
|
301
313
|
});
|
|
302
314
|
} else if (meteringRecord) {
|
|
303
315
|
await persistence.metering.commitAgent({
|
|
304
316
|
agentSessionId: attempt.agentSessionId,
|
|
305
317
|
record: meteringRecord,
|
|
306
|
-
meteringRecords: this.config.meteringRecords ?? "all",
|
|
318
|
+
meteringRecords: writes?.meteringRecords ?? this.config.meteringRecords ?? "all",
|
|
307
319
|
});
|
|
308
320
|
}
|
|
309
321
|
return await persistence.internalInferences!.complete({
|
|
@@ -332,9 +344,9 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
|
|
|
332
344
|
.catch(() => null);
|
|
333
345
|
}
|
|
334
346
|
if (this.closed && abort.signal.aborted) {
|
|
335
|
-
await this.recordShutdownInterruption(attempt, leaseToken, error, meteringRecord);
|
|
347
|
+
await this.recordShutdownInterruption(attempt, leaseToken, error, meteringRecord, writes?.meteringRecords);
|
|
336
348
|
} else {
|
|
337
|
-
await this.recordFailure(attempt, leaseToken, error, meteringRecord);
|
|
349
|
+
await this.recordFailure(attempt, leaseToken, error, meteringRecord, writes?.meteringRecords);
|
|
338
350
|
}
|
|
339
351
|
} finally {
|
|
340
352
|
clearInterval(heartbeat);
|
|
@@ -349,6 +361,7 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
|
|
|
349
361
|
leaseToken: string,
|
|
350
362
|
error: unknown,
|
|
351
363
|
meteringRecord: OperationMeteringRecord | null,
|
|
364
|
+
retention?: import("../../persistence/backend.ts").MeteringRecordRetention,
|
|
352
365
|
): Promise<void> {
|
|
353
366
|
const canRetry = attempt.attemptNumber < this.config.settings.retry.maxAttempts;
|
|
354
367
|
await this.config.persistence.transaction(async (persistence) => {
|
|
@@ -356,13 +369,13 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
|
|
|
356
369
|
await persistence.metering.commit({
|
|
357
370
|
agentConversationId: attempt.agentConversationId,
|
|
358
371
|
record: meteringRecord,
|
|
359
|
-
meteringRecords: this.config.meteringRecords ?? "all",
|
|
372
|
+
meteringRecords: retention ?? this.config.meteringRecords ?? "all",
|
|
360
373
|
});
|
|
361
374
|
} else if (meteringRecord) {
|
|
362
375
|
await persistence.metering.commitAgent({
|
|
363
376
|
agentSessionId: attempt.agentSessionId,
|
|
364
377
|
record: meteringRecord,
|
|
365
|
-
meteringRecords: this.config.meteringRecords ?? "all",
|
|
378
|
+
meteringRecords: retention ?? this.config.meteringRecords ?? "all",
|
|
366
379
|
});
|
|
367
380
|
}
|
|
368
381
|
await persistence.internalInferences!.fail({
|
|
@@ -381,6 +394,7 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
|
|
|
381
394
|
leaseToken: string,
|
|
382
395
|
error: unknown,
|
|
383
396
|
meteringRecord: OperationMeteringRecord | null,
|
|
397
|
+
retention?: import("../../persistence/backend.ts").MeteringRecordRetention,
|
|
384
398
|
): Promise<void> {
|
|
385
399
|
const strategy = this.registry.get(attempt.purpose, attempt.input.strategyId, attempt.input.version);
|
|
386
400
|
const disposition = strategy?.classifyError(error) ?? { kind: "terminal" as const, code: "unknown_strategy" };
|
|
@@ -392,13 +406,13 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
|
|
|
392
406
|
await persistence.metering.commit({
|
|
393
407
|
agentConversationId: attempt.agentConversationId,
|
|
394
408
|
record: meteringRecord,
|
|
395
|
-
meteringRecords: this.config.meteringRecords ?? "all",
|
|
409
|
+
meteringRecords: retention ?? this.config.meteringRecords ?? "all",
|
|
396
410
|
});
|
|
397
411
|
} else if (meteringRecord) {
|
|
398
412
|
await persistence.metering.commitAgent({
|
|
399
413
|
agentSessionId: attempt.agentSessionId,
|
|
400
414
|
record: meteringRecord,
|
|
401
|
-
meteringRecords: this.config.meteringRecords ?? "all",
|
|
415
|
+
meteringRecords: retention ?? this.config.meteringRecords ?? "all",
|
|
402
416
|
});
|
|
403
417
|
}
|
|
404
418
|
return await persistence.internalInferences!.fail({
|
|
@@ -269,6 +269,10 @@ export interface AgentConversationSummary {
|
|
|
269
269
|
readonly latestSequence: number;
|
|
270
270
|
readonly deletedAt?: string;
|
|
271
271
|
readonly metadata?: string;
|
|
272
|
+
/** True when the conversation was created by adopting an existing provider session. Absent otherwise. */
|
|
273
|
+
readonly adopted?: boolean;
|
|
274
|
+
/** The provider session an adoption asked for, kept so a failed adoption can be retried. */
|
|
275
|
+
readonly adoptProviderSessionId?: string;
|
|
272
276
|
}
|
|
273
277
|
|
|
274
278
|
export interface CreateAgentConversationInput {
|
|
@@ -278,6 +282,8 @@ export interface CreateAgentConversationInput {
|
|
|
278
282
|
readonly title?: string;
|
|
279
283
|
readonly createdAt?: string;
|
|
280
284
|
readonly metadata?: string;
|
|
285
|
+
/** Mark the conversation as created by adopting this provider session. */
|
|
286
|
+
readonly adoptProviderSessionId?: string;
|
|
281
287
|
}
|
|
282
288
|
|
|
283
289
|
export interface ConversationListOptions {
|
|
@@ -512,6 +518,11 @@ export interface ConversationRecordPersistence {
|
|
|
512
518
|
agentConversationId: AgentConversationId,
|
|
513
519
|
options?: RecordListOptions,
|
|
514
520
|
): Promise<ConversationRecordPage>;
|
|
521
|
+
/**
|
|
522
|
+
* Physically delete every record of a conversation, keeping the conversation itself. Returns how many were
|
|
523
|
+
* deleted. Sequence numbers are not reused. Optional: an append-only backend cannot clear a transcript.
|
|
524
|
+
*/
|
|
525
|
+
deleteForConversation?(agentConversationId: AgentConversationId): Promise<number>;
|
|
515
526
|
/** Optional efficient newest-first history API. Use list(afterSequence) for live catch-up. */
|
|
516
527
|
listRecent?(
|
|
517
528
|
agentConversationId: AgentConversationId,
|
|
@@ -538,6 +549,12 @@ export interface ProviderSessionPersistence {
|
|
|
538
549
|
append(record: ProviderSessionRecord): Promise<void>;
|
|
539
550
|
list(agentConversationId: AgentConversationId): Promise<readonly ProviderSessionRecord[]>;
|
|
540
551
|
active(agentConversationId: AgentConversationId): Promise<ProviderSessionRecord | null>;
|
|
552
|
+
/**
|
|
553
|
+
* Conversations that own this provider session: those where it is the active session, and those
|
|
554
|
+
* that asked to adopt it and have not attached it yet. Deleted conversations do not count.
|
|
555
|
+
* Optional: a backend without it cannot refuse a second adoption of the same session.
|
|
556
|
+
*/
|
|
557
|
+
conversationsUsing?(internalSessionId: string): Promise<readonly AgentConversationId[]>;
|
|
541
558
|
}
|
|
542
559
|
|
|
543
560
|
export type MeteringRecordRetention = "all" | "none" | { readonly retain: number };
|