@qlairoslabs/acp-client 0.9.3 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CONSUMER_GUIDE.md CHANGED
@@ -92,6 +92,16 @@ try {
92
92
  The user message and each assistant-message boundary are stored as separate typed rows.
93
93
  Reopen the same database with `Agent.open()` and call
94
94
  `agent.conversations.open(agentConversationId)` to continue its active provider thread.
95
+ `Agent.close()` interrupts live prompts and waits for their finalization and queued
96
+ conversation writes before closing the SQLite backend; an interrupted prompt may reject.
97
+
98
+ A newly created conversation may expose `conversation.internalSessionId` immediately, but
99
+ the provider attachment is retained only in memory until its first completed provider turn.
100
+ If the conversation stops before then, reopening the durable `agc-*` conversation creates a
101
+ fresh provider thread. After a completed turn, the provider mapping becomes the continuation
102
+ candidate used by `open()`; successfully loading it does not create another history row.
103
+ This is a local evidence threshold, not a guarantee that the harness will keep the provider
104
+ session loadable forever.
95
105
 
96
106
  ### Attach consumer data to a prompt message
97
107
 
@@ -203,13 +213,13 @@ earlier position when its first revision arrives. Configuration, protocol, agent
203
213
  actions, and metering references remain individual records unless they have an
204
214
  explicit logical identity; metering details are read from `persistence.metering`.
205
215
 
206
- For live reconciliation, subscribe before the initial read if immediate UI feedback
207
- matters, but treat subscription notifications as hints. The authoritative catch-up is
208
- `records.list(conversation.id, { afterSequence: lastSeenSequence, limit: 100 })`.
216
+ For live reconciliation, subscribe to `agent.events` (see below) before the initial read if
217
+ immediate UI feedback matters, but treat live notifications as hints. The authoritative
218
+ catch-up is `records.list(conversation.id, { afterSequence: lastSeenSequence, limit: 100 })`.
209
219
  Advance `lastSeenSequence` to the last returned record and repeat until the page is
210
220
  short. Upsert by `recordId` through `reconcileConversationTimeline`; after a process
211
- restart, catch up from the last sequence the consumer retained. Subscription sequence
212
- numbers are **not** SQLite conversation sequences.
221
+ restart, catch up from the last sequence the consumer retained. Process-local notification
222
+ counters are **not** SQLite conversation sequences.
213
223
 
214
224
  Use one batched preview read for a conversation list:
215
225
 
@@ -232,6 +242,57 @@ revision per logical message; `records.list()` and `records.listRecent()` retain
232
242
  physical revisions for timeline reconstruction and audit. `listRecent` and `listPreviews` are SQLite
233
243
  capabilities; custom persistence backends may not implement them.
234
244
 
245
+ ### Live committed-record events
246
+
247
+ `agent.events` is a process-local stream of canonical conversation records, published only
248
+ after the transaction that wrote them commits. It is not durable and has no replay: it is
249
+ the live half of the same stream `records.list()` returns, so a UI can render immediately
250
+ and still reconcile against SQLite.
251
+
252
+ ```ts
253
+ const unsubscribe = agent.events.subscribe((notification) => {
254
+ const record = notification.event.record; // the exact persisted record
255
+ applyToTimeline(record); // upsert by recordId, as a reload would
256
+ }, {
257
+ conversationIds: [conversation.id],
258
+ recordKinds: ["message", "tool_call", "permission", "activity"],
259
+ });
260
+ // later:
261
+ unsubscribe();
262
+ ```
263
+
264
+ Each event carries the record's stable `recordId` and conversation `sequence`. Evolving
265
+ records (streaming messages, tool calls, activities, thinking) emit one event per physical
266
+ revision, so reconcile by the same logical identity a reload uses.
267
+ `notification.deliverySequence` orders live events for one process but is not a durable
268
+ cursor.
269
+
270
+ Bootstrap without losing events: subscribe first, buffer, read history, then deduplicate by
271
+ `recordId`:
272
+
273
+ ```ts
274
+ const pending: ConversationRecord[] = [];
275
+ const unsubscribe = agent.events.subscribe(({ event }) => pending.push(event.record), {
276
+ conversationIds: [conversation.id],
277
+ });
278
+ const page = await agent.persistence.records.listRecent!(conversation.id, { limit: 50 });
279
+ let items = reconcileConversationTimeline([], [...page.records, ...pending]);
280
+ ```
281
+
282
+ After a restart or a missed window, catch up from SQLite with
283
+ `records.list(conversation.id, { afterSequence: lastSeenSequence })`. Filters are fixed for
284
+ the life of a subscription: omitting a list selects everything, an empty list selects
285
+ nothing, and an unknown `recordKinds` value throws at subscribe time. Filtering never
286
+ changes capture, audit, persistence, or another subscriber. A subscriber that throws is
287
+ logged and ignored; it cannot fail the operation that produced the record.
288
+
289
+ `agent.events` reports committed records only. Provisional live data — response chunks,
290
+ turn and state changes, handoff progress — still arrives through the prompt handlers and
291
+ `conversation.subscribe()`. A record may appear in both at different stages: a tool update
292
+ first streams provisionally, then arrives as a committed `tool_call`. Detached
293
+ `AgentConversation` instances without an owning `Agent` are outside this bus, and a
294
+ consumer-direct `persistence.records.append()` is not observed.
295
+
235
296
  ### Agent audit log
236
297
 
237
298
  An SQLite-backed `Agent` can copy selected observations into an independently located,
@@ -1028,6 +1089,33 @@ V0 handoff uses the current adapter. The default summary-generation and new-thre
1028
1089
  introduction prompts are library-defined, and introduction is an ordinary user prompt
1029
1090
  because ACP has no portable system-prompt field.
1030
1091
 
1092
+ ### Provider attachment
1093
+
1094
+ A newly created provider thread is not selected for a later open until a provider turn has
1095
+ completed on it. Until then the running process uses it, but a restart returns to the
1096
+ previous thread — or, for a conversation that never had one, starts fresh.
1097
+
1098
+ `HandoffResult.providerAttachment` reports which of those a transition produced:
1099
+
1100
+ ```ts
1101
+ handoff.providerAttachment === "recorded"; // a turn completed on the target
1102
+ reset.providerAttachment === "runtime_only"; // live on the target, not yet selected
1103
+ ```
1104
+
1105
+ A promptless `reset()` has no turn to confirm its target, so it reports `runtime_only` and
1106
+ the previous thread stays the restart fallback until the next completed prompt. This
1107
+ describes local state only; it never claims the provider will still accept the session.
1108
+
1109
+ `providerAttachment` is a required field, so code that constructs a `HandoffResult` value
1110
+ itself — rather than consuming one — needs updating. `AgentSessionHandoffError` gained
1111
+ `fromInternalSessionId`, `toInternalSessionId`, `providerAttachment`, `activationCompleted`,
1112
+ `summary` and `targetResult`; `activationCompleted` distinguishes a target prompt that
1113
+ failed after the target was already selected from a transition that never reached one.
1114
+
1115
+ Because a transition keeps its source alive until the target is confirmed, both
1116
+ same-adapter and cross-adapter transitions now run a second provider process for the
1117
+ duration of the transition.
1118
+
1031
1119
  ## Harness configuration and commands
1032
1120
 
1033
1121
  ACP configuration is available through the stable session:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qlairoslabs/acp-client",
3
- "version": "0.9.3",
3
+ "version": "0.10.0",
4
4
  "description": "Embeddable Agent Client Protocol (ACP) client library with degraded PTY fallback.",
5
5
  "type": "module",
6
6
  "module": "src/index.ts",
@@ -81,6 +81,13 @@ export interface ContinuationReport {
81
81
  readonly activeInternalSessionId: string;
82
82
  readonly transitionId: string;
83
83
  }
84
+ /**
85
+ * The conversation had never selected a provider thread, so a fresh one was started.
86
+ *
87
+ * Distinct from `reconstructed`: nothing was continued because no provider turn had
88
+ * ever completed on a thread this conversation recorded.
89
+ */
90
+ | { readonly kind: "fresh"; readonly activeInternalSessionId: string }
84
91
  | { readonly kind: "unavailable" };
85
92
  }
86
93
 
@@ -179,6 +186,14 @@ export interface HandoffResult {
179
186
  readonly summary: string;
180
187
  /** Result of `targetPrompt`, when one was supplied. */
181
188
  readonly targetResult?: PromptResult;
189
+ /**
190
+ * Whether the target was selected locally as the next open's continuation candidate.
191
+ *
192
+ * `runtime_only` means the running process is on the target but no provider turn has yet
193
+ * justified recording it, so a restart returns to the previous attachment. This reports
194
+ * local lifecycle state; it never claims the provider will still accept the session.
195
+ */
196
+ readonly providerAttachment: "runtime_only" | "recorded";
182
197
  /** One record per token-consuming operation the handoff performed, in order. */
183
198
  readonly meteringRecords: readonly OperationMeteringRecord[];
184
199
  }
@@ -1,3 +1,8 @@
1
+ import type { AgentConversationId, AgentSessionId } from "./agent-ids.ts";
2
+ import type {
3
+ ConversationErrorRecoverability,
4
+ ConversationErrorSource,
5
+ } from "./persistence/backend.ts";
1
6
  import type { ContinuationReport, PromptBlocker } from "./agent-conversation-contracts.ts";
2
7
 
3
8
  export class AgentSessionPromptBlockedError extends Error {
@@ -29,3 +34,53 @@ export class DirectAuditPersistenceUnsupportedError extends Error {
29
34
  }
30
35
  }
31
36
 
37
+ export interface ProviderSessionErrorDetails {
38
+ readonly agentSessionId: AgentSessionId;
39
+ readonly agentConversationId: AgentConversationId;
40
+ /** Stable identity of the failed open invocation; `${attemptId}:error` is its record id. */
41
+ readonly attemptId: string;
42
+ readonly internalSessionId?: string;
43
+ readonly code: string;
44
+ readonly source: ConversationErrorSource;
45
+ readonly recoverability: ConversationErrorRecoverability;
46
+ /** Present only when canonical capture accepted the durable error record. */
47
+ readonly recordId?: string;
48
+ /** Set when writing the durable record also failed; the provider cause stays primary. */
49
+ readonly recordingError?: Error;
50
+ /** Safe display fallback; the durable record carries the same text. */
51
+ readonly message?: string;
52
+ readonly cause?: unknown;
53
+ }
54
+
55
+ /**
56
+ * A provider session could not be created or loaded, and the operation could not return a
57
+ * live conversation. The immediate exception and the durable error record share the same
58
+ * code, attempt id, and recoverability; the record id is present only when canonical capture
59
+ * accepted the row.
60
+ */
61
+ export class ProviderSessionError extends Error {
62
+ readonly agentSessionId: AgentSessionId;
63
+ readonly agentConversationId: AgentConversationId;
64
+ readonly attemptId: string;
65
+ readonly internalSessionId?: string;
66
+ readonly code: string;
67
+ readonly source: ConversationErrorSource;
68
+ readonly recoverability: ConversationErrorRecoverability;
69
+ readonly recordId?: string;
70
+ readonly recordingError?: Error;
71
+
72
+ constructor(details: ProviderSessionErrorDetails) {
73
+ super(details.message ?? "The provider session could not be loaded.", { cause: details.cause });
74
+ this.name = "ProviderSessionError";
75
+ this.agentSessionId = details.agentSessionId;
76
+ this.agentConversationId = details.agentConversationId;
77
+ this.attemptId = details.attemptId;
78
+ if (details.internalSessionId !== undefined) this.internalSessionId = details.internalSessionId;
79
+ this.code = details.code;
80
+ this.source = details.source;
81
+ this.recoverability = details.recoverability;
82
+ if (details.recordId !== undefined) this.recordId = details.recordId;
83
+ if (details.recordingError !== undefined) this.recordingError = details.recordingError;
84
+ }
85
+ }
86
+
@@ -7,6 +7,10 @@ import type { ResponseMessage } from "./types.ts";
7
7
  import type { OperationMeteringRecord } from "./metering/record.ts";
8
8
  import type { AgentSessionMeteringState } from "./metering/state.ts";
9
9
  import type { IdentityDeliveryReceipt } from "./identity.ts";
10
+ import type {
11
+ ProviderAttachmentCommitAcknowledgement,
12
+ ProviderAttachmentState,
13
+ } from "./persistence/provider-attachment.ts";
10
14
 
11
15
  export interface OwnedPromptInput {
12
16
  readonly operationId: string;
@@ -27,6 +31,22 @@ export interface OwnedPromptPreparation {
27
31
  export interface OwnedPromptCompleted extends OwnedPromptInput {
28
32
  readonly result: AgentSessionPromptResult;
29
33
  readonly identityDeliveryReceipt?: IdentityDeliveryReceipt;
34
+ readonly providerAttachment: ProviderAttachmentState;
35
+ }
36
+
37
+ export interface OwnedPromptCommitResult {
38
+ readonly providerAttachment?: ProviderAttachmentCommitAcknowledgement;
39
+ }
40
+
41
+ /** @internal Indicates that the local prompt commit succeeded but a follow-up hook failed. */
42
+ export class OwnedPromptPostCommitError extends Error {
43
+ constructor(
44
+ readonly commit: OwnedPromptCommitResult,
45
+ cause: unknown,
46
+ ) {
47
+ super(cause instanceof Error ? cause.message : String(cause), { cause });
48
+ this.name = "OwnedPromptPostCommitError";
49
+ }
30
50
  }
31
51
 
32
52
  export interface OwnedPromptFailed extends OwnedPromptInput {
@@ -37,7 +57,7 @@ export interface OwnedPromptFailed extends OwnedPromptInput {
37
57
  /** @internal Agent-owned persistence and identity boundary for a conversation turn. */
38
58
  export interface AgentConversationOwnerLifecycle {
39
59
  beforePrompt(input: OwnedPromptInput): Promise<OwnedPromptPreparation>;
40
- afterPrompt(input: OwnedPromptCompleted): Promise<void>;
60
+ afterPrompt(input: OwnedPromptCompleted): Promise<OwnedPromptCommitResult | void>;
41
61
  promptFailed(input: OwnedPromptFailed): Promise<void>;
42
62
  /** Durably commit one normalized operation record and its bounded next state. */
43
63
  meteringRecorded?(record: OperationMeteringRecord): Promise<void>;
@@ -6,6 +6,7 @@
6
6
  export class AgentConversationQueue<T> {
7
7
  readonly #items: T[] = [];
8
8
  #draining = false;
9
+ #activeDrain: Promise<void> | null = null;
9
10
 
10
11
  get queuedCount(): number {
11
12
  return this.#items.length;
@@ -25,20 +26,37 @@ export class AgentConversationQueue<T> {
25
26
  }
26
27
 
27
28
  /**
28
- * Drain every item serially. Concurrent calls share the active drain by becoming
29
- * no-ops; an item enqueued by an active operation is observed by the same loop.
29
+ * Drain every item serially. Concurrent calls share the active drain; an item
30
+ * enqueued by an active operation is observed by the same loop.
30
31
  */
31
- async drain(execute: (item: T) => Promise<void>): Promise<void> {
32
- if (this.#draining) return;
32
+ drain(execute: (item: T) => Promise<void>): Promise<void> {
33
+ if (this.#activeDrain) return this.#activeDrain;
33
34
  this.#draining = true;
34
- try {
35
- while (this.#items.length > 0) {
36
- const item = this.#items.shift()!;
37
- await execute(item);
35
+ let resolveDrain!: () => void;
36
+ let rejectDrain!: (error: unknown) => void;
37
+ const active = new Promise<void>((resolve, reject) => {
38
+ resolveDrain = resolve;
39
+ rejectDrain = reject;
40
+ });
41
+ // Install the waitable promise before invoking execute: callbacks may call
42
+ // stop() synchronously while the first item is being started.
43
+ this.#activeDrain = active;
44
+ void (async () => {
45
+ try {
46
+ while (this.#items.length > 0) {
47
+ const item = this.#items.shift()!;
48
+ await execute(item);
49
+ }
50
+ } finally {
51
+ this.#draining = false;
52
+ this.#activeDrain = null;
38
53
  }
39
- } finally {
40
- this.#draining = false;
41
- }
54
+ })().then(resolveDrain, rejectDrain);
55
+ return active;
42
56
  }
43
- }
44
57
 
58
+ /** Wait for the active executor, including its current item's finalization. */
59
+ waitForIdle(): Promise<void> {
60
+ return this.#activeDrain ?? Promise.resolve();
61
+ }
62
+ }