@qlairoslabs/acp-client 0.10.1 → 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 (42) hide show
  1. package/CONSUMER_GUIDE.md +252 -0
  2. package/README.md +0 -3
  3. package/package.json +1 -1
  4. package/src/agent/adoption/config.ts +57 -0
  5. package/src/agent/adoption/index.ts +8 -0
  6. package/src/agent/adoption/provider-session-delete.ts +27 -0
  7. package/src/agent/adoption/provider-sessions.ts +73 -0
  8. package/src/agent/adoption/recap.ts +15 -0
  9. package/src/agent/adoption/replay.ts +84 -0
  10. package/src/agent/config.ts +182 -0
  11. package/src/agent/conversation-manager.ts +1006 -0
  12. package/src/agent/manager-settings.ts +46 -0
  13. package/src/agent/persisted-lifecycle.ts +309 -0
  14. package/src/agent/persistence-policy/index.ts +8 -0
  15. package/src/agent/persistence-policy/resolver.ts +118 -0
  16. package/src/agent/persistence-policy/types.ts +50 -0
  17. package/src/agent/record-capture.ts +243 -0
  18. package/src/agent-conversation-contracts.ts +11 -0
  19. package/src/agent-conversation-errors.ts +24 -0
  20. package/src/agent-conversation-owner.ts +7 -0
  21. package/src/agent-conversation-queue.ts +23 -0
  22. package/src/agent-session.ts +236 -66
  23. package/src/agent.ts +63 -1223
  24. package/src/audit/config.ts +29 -0
  25. package/src/audit/index.ts +1 -0
  26. package/src/checkpointing/contracts.ts +2 -0
  27. package/src/checkpointing/persistence/sqlite-repository.ts +13 -0
  28. package/src/checkpointing/strategy.ts +11 -5
  29. package/src/client.ts +25 -2
  30. package/src/controller.ts +3 -0
  31. package/src/index.ts +24 -0
  32. package/src/internal-inference/contracts.ts +23 -0
  33. package/src/internal-inference/coordination/manager.ts +22 -8
  34. package/src/persistence/backend.ts +17 -0
  35. package/src/persistence/sqlite-backend.ts +30 -4
  36. package/src/persistence/sqlite-provider-sessions.ts +35 -0
  37. package/src/persistence/sqlite-schema.ts +13 -3
  38. package/src/steering/combine.ts +56 -0
  39. package/src/steering/contracts.ts +84 -0
  40. package/src/steering/controller.ts +205 -0
  41. package/src/steering/index.ts +14 -0
  42. package/src/transport/acp-transport.ts +11 -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 };
@@ -1,4 +1,5 @@
1
1
  import type { AgentMode } from "./controller.ts";
2
+ import type { MessageEvent, PendingMessageId, PromptEndedBy } from "./steering/contracts.ts";
2
3
  import type { Adapter } from "./adapters.ts";
3
4
  import type { ContextWindowStatus, ProviderCostSnapshot } from "./metering/context.ts";
4
5
  import type { OperationMeteringRecord } from "./metering/record.ts";
@@ -204,6 +205,7 @@ export type AgentSessionEvent =
204
205
  | { kind: "turn_started"; turnId: string }
205
206
  | { kind: "turn_completed"; turnId: string; result: PromptResult }
206
207
  | { kind: "turn_failed"; turnId: string; error: string }
208
+ | MessageEvent
207
209
  | { kind: "presentation_recorded"; item: TranscriptPresentationItem }
208
210
  | { kind: "internal_session_commands_changed"; commands: readonly InternalSessionCommand[] }
209
211
  | { kind: "handoff_started"; handoffId: string; fromInternalSessionId: string | null }
@@ -252,6 +254,13 @@ export interface AgentSessionPromptResult extends PromptResult {
252
254
  readonly operationId: string;
253
255
  /** Null only when a queued prompt was cancelled before provider dispatch. */
254
256
  readonly metering: OperationMeteringRecord | null;
257
+ /**
258
+ * Why this turn was cancelled, when steering or `interrupt()` cancelled it and the provider really
259
+ * stopped it (`stopReason: "cancelled"`). Absent when the turn ended on its own.
260
+ */
261
+ readonly endedBy?: PromptEndedBy;
262
+ /** The messages sent after this turn was cancelled by steering or `interrupt()`, in order. */
263
+ readonly followedBy?: readonly PendingMessageId[];
255
264
  }
256
265
 
257
266
  /** Ordered envelope delivered to every current AgentSession subscriber. */
@@ -291,4 +300,6 @@ export type ProviderSession =
291
300
  readonly internalSessionId: string;
292
301
  /** Default "error": never silently replace a requested thread. */
293
302
  readonly onFailure?: "error" | "new";
303
+ /** Receives the history the loaded thread replays (raw `session/update` notifications). */
304
+ readonly onReplay?: (notification: unknown) => void;
294
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
+ }
@@ -3,6 +3,7 @@ import type { Adapter } from "./adapters.ts";
3
3
  import type { AgentMode } from "./controller.ts";
4
4
  import type { NewConversationRecord, ParticipantRef, PersistenceJsonValue } from "./persistence/backend.ts";
5
5
  import type { AgentSessionPromptResult } from "./agent-conversation-contracts.ts";
6
+ import type { PromptPart } from "./steering/contracts.ts";
6
7
  import type { ResponseMessage } from "./types.ts";
7
8
  import type { OperationMeteringRecord } from "./metering/record.ts";
8
9
  import type { AgentSessionMeteringState } from "./metering/state.ts";
@@ -19,12 +20,16 @@ export interface OwnedPromptInput {
19
20
  readonly targetProviderContextId?: string;
20
21
  readonly participantId?: string;
21
22
  readonly consumerMetadata?: PersistenceJsonValue;
23
+ /** Present when several messages were combined into this one prompt: each is recorded as sent. */
24
+ readonly parts?: readonly PromptPart[];
22
25
  readonly text: string;
23
26
  }
24
27
 
25
28
  export interface OwnedPromptPreparation {
26
29
  readonly providerText?: string;
27
30
  readonly participant?: ParticipantRef;
31
+ /** Every participant of a combined prompt, in order. `participant` is the first. */
32
+ readonly participants?: readonly ParticipantRef[];
28
33
  readonly identityDeliveryReceipt?: IdentityDeliveryReceipt;
29
34
  }
30
35
 
@@ -57,6 +62,8 @@ export interface OwnedPromptFailed extends OwnedPromptInput {
57
62
  /** @internal Agent-owned persistence and identity boundary for a conversation turn. */
58
63
  export interface AgentConversationOwnerLifecycle {
59
64
  beforePrompt(input: OwnedPromptInput): Promise<OwnedPromptPreparation>;
65
+ /** The participant that history imported from an adopted provider session is attributed to. */
66
+ importParticipant?(): Promise<ParticipantRef>;
60
67
  afterPrompt(input: OwnedPromptCompleted): Promise<OwnedPromptCommitResult | void>;
61
68
  promptFailed(input: OwnedPromptFailed): Promise<void>;
62
69
  /** Durably commit one normalized operation record and its bounded next state. */
@@ -25,6 +25,29 @@ export class AgentConversationQueue<T> {
25
25
  return this.#items.splice(0);
26
26
  }
27
27
 
28
+ /** The next queued item, without removing it. */
29
+ peek(): T | undefined {
30
+ return this.#items[0];
31
+ }
32
+
33
+ /** Queued (not active) work in FIFO order. The returned array is a copy. */
34
+ snapshot(): readonly T[] {
35
+ return [...this.#items];
36
+ }
37
+
38
+ /** Remove and return the first queued item the predicate accepts, if any. */
39
+ remove(predicate: (item: T) => boolean): T | undefined {
40
+ const index = this.#items.findIndex(predicate);
41
+ return index < 0 ? undefined : this.#items.splice(index, 1)[0];
42
+ }
43
+
44
+ /** Remove and return the consecutive items at the head of the queue the predicate accepts. */
45
+ takeWhile(predicate: (item: T) => boolean): T[] {
46
+ let count = 0;
47
+ while (count < this.#items.length && predicate(this.#items[count]!)) count += 1;
48
+ return this.#items.splice(0, count);
49
+ }
50
+
28
51
  /**
29
52
  * Drain every item serially. Concurrent calls share the active drain; an item
30
53
  * enqueued by an active operation is observed by the same loop.