@qlairoslabs/acp-client 0.10.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CONSUMER_GUIDE.md +153 -0
  2. package/package.json +1 -1
  3. package/src/agent/adoption/config.ts +57 -0
  4. package/src/agent/adoption/index.ts +8 -0
  5. package/src/agent/adoption/provider-session-delete.ts +27 -0
  6. package/src/agent/adoption/provider-sessions.ts +73 -0
  7. package/src/agent/adoption/recap.ts +15 -0
  8. package/src/agent/adoption/replay.ts +84 -0
  9. package/src/agent/config.ts +182 -0
  10. package/src/agent/conversation-manager.ts +1006 -0
  11. package/src/agent/manager-settings.ts +46 -0
  12. package/src/agent/persisted-lifecycle.ts +309 -0
  13. package/src/agent/persistence-policy/index.ts +8 -0
  14. package/src/agent/persistence-policy/resolver.ts +118 -0
  15. package/src/agent/persistence-policy/types.ts +50 -0
  16. package/src/agent/record-capture.ts +243 -0
  17. package/src/agent-conversation-contracts.ts +2 -0
  18. package/src/agent-conversation-errors.ts +24 -0
  19. package/src/agent-conversation-owner.ts +2 -0
  20. package/src/agent-session.ts +115 -1
  21. package/src/agent.ts +63 -1233
  22. package/src/audit/config.ts +29 -0
  23. package/src/audit/index.ts +1 -0
  24. package/src/checkpointing/contracts.ts +2 -0
  25. package/src/checkpointing/persistence/sqlite-repository.ts +13 -0
  26. package/src/checkpointing/strategy.ts +11 -5
  27. package/src/client.ts +22 -1
  28. package/src/controller.ts +3 -0
  29. package/src/index.ts +14 -0
  30. package/src/internal-inference/contracts.ts +23 -0
  31. package/src/internal-inference/coordination/manager.ts +22 -8
  32. package/src/persistence/backend.ts +17 -0
  33. package/src/persistence/sqlite-backend.ts +30 -4
  34. package/src/persistence/sqlite-provider-sessions.ts +35 -0
  35. package/src/persistence/sqlite-schema.ts +13 -3
  36. package/src/transport/acp-transport.ts +3 -0
@@ -0,0 +1,243 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ type AgentConversationId,
4
+ } from "../agent-ids.ts";
5
+ import {
6
+ AgentAdapterRegistry,
7
+ } from "../agent-adapter-registry.ts";
8
+ import type { MeteredOperationKind } from "../metering/record.ts";
9
+ import {
10
+ NoopAgentIdentityRuntime,
11
+ composeIdentityPrompt,
12
+ } from "../identity.ts";
13
+ import {
14
+ IMPLICIT_USER_PARTICIPANT_ID,
15
+ PersistenceCapabilityError,
16
+ normalizeParticipantRef,
17
+ shouldCaptureProtocolMethod,
18
+ type ConversationErrorDetails,
19
+ type ConversationRecord,
20
+ type NewConversationRecord,
21
+ type ParticipantRef,
22
+ type PersistenceBackend,
23
+ type PersistenceScope,
24
+ type RecordCaptureLevel,
25
+ } from "../persistence/backend.ts";
26
+ import {
27
+ projectAgentAuditObservation,
28
+ type NormalizedAgentObservation,
29
+ type ResolvedAgentAuditLogConfig,
30
+ } from "../audit/index.ts";
31
+ import { buildConversationErrorDetails } from "../persistence/error-records.ts";
32
+
33
+
34
+ import type { Agent } from "../agent.ts";
35
+ import type { ManagerSettings } from "./manager-settings.ts";
36
+
37
+ export async function updateConversationIdentity(
38
+ agent: Agent,
39
+ settings: ManagerSettings,
40
+ conversationId: AgentConversationId,
41
+ records: readonly ConversationRecord[],
42
+ ): Promise<void> {
43
+ await agent.identity.update({
44
+ agentSessionId: agent.id,
45
+ agentConversationId: conversationId,
46
+ records,
47
+ });
48
+ // A conversation kept out of the audit stream causes no `identity` entry either.
49
+ if (settings.auditLog) await settings.auditIdentityUpdate(conversationId, records);
50
+ }
51
+
52
+ /**
53
+ * Append one canonical record about a conversation under that conversation's capture and audit policy, inside
54
+ * the given transaction. Returns the stored record, or `undefined` when capture dropped it.
55
+ */
56
+ export async function appendCanonicalRecord(
57
+ settings: ManagerSettings,
58
+ persistence: PersistenceScope,
59
+ record: NewConversationRecord,
60
+ ): Promise<ConversationRecord | undefined> {
61
+ const persisted: ConversationRecord[] = [];
62
+ await persistObservationsInTransaction(settings, persistence, [record], true, persisted);
63
+ return persisted[0];
64
+ }
65
+
66
+ /** Persist canonical records and their audit intents in one transaction, then publish them. */
67
+ export async function persistConversationObservations(
68
+ agent: Agent,
69
+ settings: ManagerSettings,
70
+ records: readonly NewConversationRecord[],
71
+ audit = true,
72
+ ): Promise<readonly ConversationRecord[]> {
73
+ if (records.length === 0) return Object.freeze([]);
74
+ if ((!audit || !settings.auditLog) && records.every((record) => {
75
+ if (record.kind !== "protocol") return settings.capture[record.kind] === "none";
76
+ return settings.capture.protocol.level === "none"
77
+ || !shouldCaptureProtocolMethod(settings.capture.protocol, record.method);
78
+ })) return Object.freeze([]);
79
+ const persisted: ConversationRecord[] = [];
80
+ await agent.persistence.transaction(async (persistence) => {
81
+ await persistObservationsInTransaction(settings, persistence, records, audit, persisted);
82
+ });
83
+ agent.publishCommittedRecords(persisted);
84
+ if (audit && settings.auditLog) agent.audit?.notifyPending();
85
+ return Object.freeze(persisted);
86
+ }
87
+
88
+ export async function persistObservationsInTransaction(
89
+ settings: ManagerSettings,
90
+ persistence: PersistenceScope,
91
+ records: readonly NewConversationRecord[],
92
+ audit: boolean,
93
+ persisted: ConversationRecord[],
94
+ ): Promise<void> {
95
+ for (const record of records) {
96
+ const level = record.kind === "protocol"
97
+ ? settings.capture.protocol.level
98
+ : settings.capture[record.kind];
99
+ const canonicalAccepted = level !== "none" && (
100
+ record.kind !== "protocol"
101
+ || shouldCaptureProtocolMethod(settings.capture.protocol, record.method)
102
+ );
103
+ if (canonicalAccepted) {
104
+ persisted.push(await persistence.records.append(captureRuntimeRecord(record, level)));
105
+ }
106
+ if (audit && settings.auditLog) {
107
+ await enqueueAuditObservation(persistence, {
108
+ scope: "conversation",
109
+ sourceObservationId: record.recordId,
110
+ operationId: operationIdFromMetadata(record.metadata),
111
+ record,
112
+ }, settings.auditLog);
113
+ }
114
+ }
115
+ }
116
+
117
+ export function normalizeParticipants(participants?: readonly ParticipantRef[]): readonly ParticipantRef[] {
118
+ const values = participants?.length
119
+ ? participants.map(normalizeParticipantRef)
120
+ : [{ id: IMPLICIT_USER_PARTICIPANT_ID, kind: "user" as const }];
121
+ const seen = new Set<string>();
122
+ for (const participant of values) {
123
+ if (seen.has(participant.id)) throw new Error(`duplicate participant id: ${participant.id}`);
124
+ seen.add(participant.id);
125
+ }
126
+ return Object.freeze(values);
127
+ }
128
+
129
+ export function internalInferenceMeteringKind(purpose: string): MeteredOperationKind {
130
+ if (
131
+ purpose === "conversation_checkpoint"
132
+ || purpose === "conversation_recovery"
133
+ || purpose === "identity_update"
134
+ ) return purpose;
135
+ return "internal_command";
136
+ }
137
+
138
+ export function captureRuntimeRecord(
139
+ record: NewConversationRecord,
140
+ level: RecordCaptureLevel,
141
+ ): NewConversationRecord {
142
+ if (record.kind === "error") {
143
+ // `metadata` omits the display message and details; `content` keeps the message but
144
+ // still omits details; `raw` retains the allow-listed details.
145
+ if (level === "raw") return record;
146
+ const { details: _details, message, ...rest } = record;
147
+ return level === "content"
148
+ ? { ...rest, ...(message === undefined ? {} : { message }) }
149
+ : rest;
150
+ }
151
+ if (level !== "metadata") return record;
152
+ switch (record.kind) {
153
+ case "message":
154
+ return { ...record, content: "" };
155
+ case "tool_call":
156
+ return {
157
+ recordId: record.recordId,
158
+ agentSessionId: record.agentSessionId,
159
+ agentConversationId: record.agentConversationId,
160
+ kind: record.kind,
161
+ timestamp: record.timestamp,
162
+ ...(record.metadata ? { metadata: record.metadata } : {}),
163
+ toolCallId: record.toolCallId,
164
+ state: record.state,
165
+ ...(record.name ? { name: record.name } : {}),
166
+ };
167
+ case "permission":
168
+ return {
169
+ recordId: record.recordId,
170
+ agentSessionId: record.agentSessionId,
171
+ agentConversationId: record.agentConversationId,
172
+ kind: record.kind,
173
+ timestamp: record.timestamp,
174
+ ...(record.metadata ? { metadata: record.metadata } : {}),
175
+ permissionId: record.permissionId,
176
+ state: record.state,
177
+ ...(record.outcome ? { outcome: record.outcome } : {}),
178
+ };
179
+ case "configuration":
180
+ return { ...record, value: undefined };
181
+ case "protocol":
182
+ return { ...record, message: undefined };
183
+ case "native_action":
184
+ case "agent_action":
185
+ return { ...record, input: undefined, output: undefined };
186
+ case "thinking":
187
+ return { ...record, content: "" };
188
+ case "activity":
189
+ return { ...record, content: undefined, data: undefined };
190
+ case "metering":
191
+ return record;
192
+ }
193
+ }
194
+
195
+ export async function enqueueAuditObservation(
196
+ persistence: PersistenceBackend | PersistenceScope,
197
+ observation: NormalizedAgentObservation,
198
+ config: ResolvedAgentAuditLogConfig,
199
+ ): Promise<void> {
200
+ const projected = projectAgentAuditObservation(observation, config.capture);
201
+ if (!projected) return;
202
+ if (!persistence.auditOutbox) throw new PersistenceCapabilityError("auditOutbox");
203
+ await persistence.auditOutbox.enqueue({
204
+ outboxId: `aud-${randomUUID()}`,
205
+ sourceObservationId: projected.sourceObservationId,
206
+ ...(projected.sourceRecordId ? { sourceRecordId: projected.sourceRecordId } : {}),
207
+ ...(projected.operationId ? { operationId: projected.operationId } : {}),
208
+ ...(projected.agentConversationId ? { agentConversationId: projected.agentConversationId } : {}),
209
+ occurredAt: projected.occurredAt,
210
+ kind: projected.kind,
211
+ captureLevel: projected.captureLevel,
212
+ captureFingerprint: config.captureFingerprint,
213
+ payload: projected.payload,
214
+ createdAt: new Date().toISOString(),
215
+ });
216
+ }
217
+
218
+ /** Allow-listed machine-readable detail from a raw ACP error, when it exposes any. */
219
+ export function providerSessionErrorDetails(error: unknown): ConversationErrorDetails | undefined {
220
+ const value = typeof error === "object" && error !== null
221
+ ? error as { code?: unknown; data?: unknown }
222
+ : null;
223
+ const data = typeof value?.data === "object" && value.data !== null
224
+ ? value.data as Record<string, unknown>
225
+ : undefined;
226
+ return buildConversationErrorDetails({
227
+ rpcCode: typeof value?.code === "number" ? value.code : undefined,
228
+ service: data?.service,
229
+ providerCode: data?.providerCode,
230
+ });
231
+ }
232
+
233
+ export function operationIdFromMetadata(metadata: string | undefined): string | undefined {
234
+ if (!metadata) return undefined;
235
+ try {
236
+ const value = JSON.parse(metadata) as { operationId?: unknown };
237
+ return typeof value.operationId === "string" && value.operationId ? value.operationId : undefined;
238
+ } catch {
239
+ return undefined;
240
+ }
241
+ }
242
+
243
+ export { AgentAdapterRegistry, NoopAgentIdentityRuntime, composeIdentityPrompt };
@@ -300,4 +300,6 @@ export type ProviderSession =
300
300
  readonly internalSessionId: string;
301
301
  /** Default "error": never silently replace a requested thread. */
302
302
  readonly onFailure?: "error" | "new";
303
+ /** Receives the history the loaded thread replays (raw `session/update` notifications). */
304
+ readonly onReplay?: (notification: unknown) => void;
303
305
  };
@@ -84,3 +84,27 @@ export class ProviderSessionError extends Error {
84
84
  }
85
85
  }
86
86
 
87
+
88
+ /**
89
+ * A provider session cannot be adopted because a conversation already owns it (or has asked to adopt it).
90
+ * `ownedBy` names the conversation(s), so a consumer can open the existing one instead.
91
+ */
92
+ export class ProviderSessionInUseError extends Error {
93
+ readonly code = "provider_session_in_use";
94
+ constructor(
95
+ readonly providerSessionId: string,
96
+ readonly ownedBy: readonly AgentConversationId[],
97
+ ) {
98
+ super(`provider session ${providerSessionId} is already used by conversation ${ownedBy.join(", ")}`);
99
+ this.name = "ProviderSessionInUseError";
100
+ }
101
+ }
102
+
103
+ /** The agent does not advertise `session/list`, so its sessions cannot be listed. */
104
+ export class ProviderSessionListUnsupportedError extends Error {
105
+ readonly code = "provider_session_list_unsupported";
106
+ constructor(readonly adapterId: string) {
107
+ super(`adapter ${adapterId} does not advertise session/list, so its sessions cannot be listed`);
108
+ this.name = "ProviderSessionListUnsupportedError";
109
+ }
110
+ }
@@ -62,6 +62,8 @@ export interface OwnedPromptFailed extends OwnedPromptInput {
62
62
  /** @internal Agent-owned persistence and identity boundary for a conversation turn. */
63
63
  export interface AgentConversationOwnerLifecycle {
64
64
  beforePrompt(input: OwnedPromptInput): Promise<OwnedPromptPreparation>;
65
+ /** The participant that history imported from an adopted provider session is attributed to. */
66
+ importParticipant?(): Promise<ParticipantRef>;
65
67
  afterPrompt(input: OwnedPromptCompleted): Promise<OwnedPromptCommitResult | void>;
66
68
  promptFailed(input: OwnedPromptFailed): Promise<void>;
67
69
  /** Durably commit one normalized operation record and its bounded next state. */
@@ -162,6 +162,7 @@ import type {
162
162
  TranscriptContinuationBuilderContext,
163
163
  } from "./agent-conversation-contracts.ts";
164
164
  import { AgentConversationQueue } from "./agent-conversation-queue.ts";
165
+ import type { ImportedTurn } from "./agent/adoption/replay.ts";
165
166
  import {
166
167
  SteeringController,
167
168
  type PendingMessage,
@@ -187,6 +188,8 @@ export {
187
188
  ContinuationUnavailableError,
188
189
  DirectAuditPersistenceUnsupportedError,
189
190
  ProviderSessionError,
191
+ ProviderSessionInUseError,
192
+ ProviderSessionListUnsupportedError,
190
193
  } from "./agent-conversation-errors.ts";
191
194
  export type { ProviderSessionErrorDetails } from "./agent-conversation-errors.ts";
192
195
  export type {
@@ -641,6 +644,9 @@ export class AgentConversation implements AgentClient, Bridgeable {
641
644
  sessionLoadFailure: providerSession.kind === "load"
642
645
  ? providerSession.onFailure ?? "error"
643
646
  : undefined,
647
+ ...(providerSession.kind === "load" && providerSession.onReplay
648
+ ? { onSessionReplay: providerSession.onReplay }
649
+ : {}),
644
650
  });
645
651
  this.bindController(this.controller);
646
652
  }
@@ -649,7 +655,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
649
655
  adapter: Adapter,
650
656
  adapterId: string,
651
657
  mode: AgentMode,
652
- startup: Pick<AgentControllerConfig, "sessionId" | "sessionLoadFailure"> = {},
658
+ startup: Pick<AgentControllerConfig, "sessionId" | "sessionLoadFailure" | "onSessionReplay"> = {},
653
659
  ): AgentController {
654
660
  return new AgentController({
655
661
  ...this.controllerDefaults,
@@ -1974,6 +1980,114 @@ export class AgentConversation implements AgentClient, Bridgeable {
1974
1980
  });
1975
1981
  }
1976
1982
 
1983
+ /**
1984
+ * @internal Store the history of an adopted provider session as records, as if its turns had run here.
1985
+ * Messages and activity (tool calls, thoughts) go through the same folding and the same capture policy as a
1986
+ * live turn; nothing is sent to the provider. Imported records carry `imported: true` in their metadata and
1987
+ * the time of the import, since a replay has no timestamps.
1988
+ */
1989
+ async importHistory(turns: readonly ImportedTurn[], importId: string): Promise<void> {
1990
+ const lifecycle = this.ownerLifecycle;
1991
+ if (!this.ownerAgentSessionId || !lifecycle?.record) return;
1992
+ const user = await lifecycle.importParticipant?.();
1993
+ for (const [index, turn] of turns.entries()) {
1994
+ const turnId = `${importId}-${index + 1}`;
1995
+ this.beginTurn(turnId);
1996
+ let users = 0;
1997
+ let assistants = 0;
1998
+ for (const item of turn.items) {
1999
+ if (item.kind === "activity") {
2000
+ this.queueActivityRecords(turnId, this.presentation.applyActivity(item.event).emitted);
2001
+ continue;
2002
+ }
2003
+ // A message settles any reasoning before it, as in a live turn.
2004
+ const settled = this.presentation.closeReasoningBoundary();
2005
+ if (settled) this.queueActivityRecords(turnId, [settled]);
2006
+ const metadata = JSON.stringify({
2007
+ operationId: turnId,
2008
+ imported: true,
2009
+ ...(item.messageId ? { providerMessageId: item.messageId } : {}),
2010
+ });
2011
+ if (item.kind === "user") {
2012
+ users += 1;
2013
+ await this.recordOwned({
2014
+ recordId: users === 1 ? `${turnId}:user` : `${turnId}:user:${users}`,
2015
+ agentSessionId: this.ownerAgentSessionId,
2016
+ agentConversationId: this.agentConversationId,
2017
+ kind: "message",
2018
+ timestamp: new Date().toISOString(),
2019
+ role: "user",
2020
+ ...(user ? { participantId: user.id } : {}),
2021
+ content: item.text,
2022
+ status: "completed",
2023
+ metadata,
2024
+ });
2025
+ } else {
2026
+ assistants += 1;
2027
+ await this.recordOwned({
2028
+ recordId: `${turnId}:assistant:${assistants}`,
2029
+ agentSessionId: this.ownerAgentSessionId,
2030
+ agentConversationId: this.agentConversationId,
2031
+ kind: "message",
2032
+ timestamp: new Date().toISOString(),
2033
+ role: "assistant",
2034
+ logicalMessageId: `message:${turnId}:assistant:${assistants}`,
2035
+ content: item.text,
2036
+ status: "completed",
2037
+ metadata,
2038
+ });
2039
+ }
2040
+ }
2041
+ this.endTurn(turnId);
2042
+ }
2043
+ await this.ownerRecordWrite;
2044
+ }
2045
+
2046
+ /**
2047
+ * @internal Ask the provider session to summarize its own history, as a hidden turn: the exchange is metered
2048
+ * and leaves a native action record, but is not a message of this conversation. Used right after an adoption,
2049
+ * before the conversation is handed to its owner, so nothing can interleave with it.
2050
+ */
2051
+ async requestRecap(instruction: string, recapId: string): Promise<string> {
2052
+ if (!instruction.trim()) throw new Error("recap instruction cannot be blank");
2053
+ const records: OperationMeteringRecord[] = [];
2054
+ await this.recordNativeAction(recapId, "adoption_recap", "started");
2055
+ try {
2056
+ const result = await this.meteredInternalPrompt(recapId, "conversation_checkpoint", instruction, records);
2057
+ if (result.status !== "completed") throw new Error(`adoption recap ${result.status}`);
2058
+ const summary = formatResponseMessages(result.messages, "\n\n").trim();
2059
+ if (!summary) throw new Error("adoption recap returned an empty summary");
2060
+ await this.recordNativeAction(recapId, "adoption_recap", "completed", { output: { chars: summary.length } });
2061
+ return summary;
2062
+ } catch (error) {
2063
+ await this.recordNativeAction(recapId, "adoption_recap", "failed", {
2064
+ error: error instanceof Error ? error.message : String(error),
2065
+ }).catch(() => undefined);
2066
+ throw error;
2067
+ }
2068
+ }
2069
+
2070
+ /**
2071
+ * @internal Store a recap as an assistant message, marked with `origin` in its metadata so it can be told
2072
+ * from something the model said in a turn. It goes through the same capture policy as every message, and
2073
+ * identity delivers it to the Agent's other conversations like any other.
2074
+ */
2075
+ async recordRecap(summary: string, recapId: string, origin: string): Promise<void> {
2076
+ if (!this.ownerAgentSessionId || !this.ownerLifecycle?.record) return;
2077
+ await this.recordOwned({
2078
+ recordId: `${recapId}:assistant:1`,
2079
+ agentSessionId: this.ownerAgentSessionId,
2080
+ agentConversationId: this.agentConversationId,
2081
+ kind: "message",
2082
+ timestamp: new Date().toISOString(),
2083
+ role: "assistant",
2084
+ logicalMessageId: `message:${recapId}:assistant:1`,
2085
+ content: summary,
2086
+ status: "completed",
2087
+ metadata: JSON.stringify({ operationId: recapId, origin, imported: true }),
2088
+ });
2089
+ }
2090
+
1977
2091
  /** @internal Seed a newly created provider thread from a durable recovery checkpoint. */
1978
2092
  async seedRecoveryContext(text: string): Promise<PromptResult> {
1979
2093
  if (!text.trim()) throw new Error("recovery context cannot be blank");