@qlairoslabs/acp-client 0.9.4 → 0.10.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.
@@ -19,6 +19,7 @@ export interface AgentAuditCaptureConfig {
19
19
  readonly agent_action?: RecordCaptureLevel;
20
20
  readonly thinking?: RecordCaptureLevel;
21
21
  readonly activity?: RecordCaptureLevel;
22
+ readonly error?: RecordCaptureLevel;
22
23
  readonly metering?: "none" | "metadata" | "summary" | "raw";
23
24
  readonly agent_lifecycle?: RecordCaptureLevel;
24
25
  readonly identity?: RecordCaptureLevel;
@@ -54,6 +55,7 @@ export interface ResolvedAgentAuditCapturePolicy {
54
55
  readonly agent_action: RecordCaptureLevel;
55
56
  readonly thinking: RecordCaptureLevel;
56
57
  readonly activity: RecordCaptureLevel;
58
+ readonly error: RecordCaptureLevel;
57
59
  readonly metering: "none" | "metadata" | "summary" | "raw";
58
60
  readonly agent_lifecycle: RecordCaptureLevel;
59
61
  readonly identity: RecordCaptureLevel;
@@ -80,6 +82,7 @@ export const DEFAULT_AGENT_AUDIT_CAPTURE: ResolvedAgentAuditCapturePolicy = Obje
80
82
  agent_action: "metadata",
81
83
  thinking: "none",
82
84
  activity: "metadata",
85
+ error: "content",
83
86
  metering: "summary",
84
87
  agent_lifecycle: "metadata",
85
88
  identity: "metadata",
@@ -166,6 +169,7 @@ export function resolveAgentAuditCapture(
166
169
  agent_action: general("agent_action"),
167
170
  thinking: general("thinking"),
168
171
  activity: general("activity"),
172
+ error: general("error"),
169
173
  metering: specialized("metering", ["none", "metadata", "summary", "raw"]),
170
174
  agent_lifecycle: general("agent_lifecycle"),
171
175
  identity: general("identity"),
@@ -90,6 +90,17 @@ function projectRecordPayload(
90
90
  return { ...base, activityId: record.activityId, activityType: record.activityType, state: record.state,
91
91
  ...(level !== "metadata" && record.content !== undefined ? { content: json(record.content) } : {}),
92
92
  ...(level === "raw" && record.data !== undefined ? { data: record.data } : {}) };
93
+ case "error":
94
+ return {
95
+ ...base,
96
+ source: record.source,
97
+ code: record.code,
98
+ recoverability: record.recoverability,
99
+ ...(record.transitionId ? { transitionId: record.transitionId } : {}),
100
+ ...(record.internalSessionId ? { internalSessionId: record.internalSessionId } : {}),
101
+ ...(level !== "metadata" && record.message ? { message: record.message } : {}),
102
+ ...(level === "raw" && record.details ? { details: json(record.details) } : {}),
103
+ };
93
104
  case "metering": {
94
105
  const metering = observation.meteringRecord;
95
106
  if (level === "raw" && metering) return json(metering);
@@ -1,5 +1,8 @@
1
1
  import type { AgentConversationId } from "../agent-ids.ts";
2
- import type { ConversationMessagePersistence } from "../persistence/backend.ts";
2
+ import type {
3
+ ConversationErrorRecoverability,
4
+ ConversationMessagePersistence,
5
+ } from "../persistence/backend.ts";
3
6
  import type { ConversationRecoveryCheckpoint } from "./contracts.ts";
4
7
  import type { ResolvedConversationRecoveryConfig } from "./config.ts";
5
8
 
@@ -51,6 +54,25 @@ function isRecord(value: unknown): value is Record<string, unknown> {
51
54
  return typeof value === "object" && value !== null && !Array.isArray(value);
52
55
  }
53
56
 
57
+ export interface ProviderSessionLoadClassification {
58
+ readonly missing: boolean;
59
+ readonly code: "provider_session_missing" | "provider_session_load_failed";
60
+ readonly recoverability: ConversationErrorRecoverability;
61
+ }
62
+
63
+ /**
64
+ * Classify a failed `session/load` conservatively. A recognized missing-session signal is
65
+ * recoverable from a checkpoint; anything else stays `unknown` rather than guessing.
66
+ */
67
+ export function classifyProviderSessionLoadError(
68
+ error: unknown,
69
+ override?: (error: unknown) => boolean,
70
+ ): ProviderSessionLoadClassification {
71
+ return isMissingProviderSessionError(error, override)
72
+ ? { missing: true, code: "provider_session_missing", recoverability: "recoverable" }
73
+ : { missing: false, code: "provider_session_load_failed", recoverability: "unknown" };
74
+ }
75
+
54
76
  export async function buildRecoverySeed(
55
77
  messages: ConversationMessagePersistence,
56
78
  conversationId: AgentConversationId,
@@ -79,7 +79,7 @@ implements InternalInferenceStrategy<ConversationCheckpointPayload> {
79
79
  generatorInternalInferenceId: result.internalInferenceId,
80
80
  summary,
81
81
  });
82
- await context.persistence.records.append({
82
+ const appended = await context.persistence.records.append({
83
83
  recordId: `${result.internalInferenceId}:checkpoint`,
84
84
  agentSessionId: context.attempt.agentSessionId,
85
85
  agentConversationId: conversationId,
@@ -93,6 +93,9 @@ implements InternalInferenceStrategy<ConversationCheckpointPayload> {
93
93
  coveredSequence: checkpoint.coveredSequence,
94
94
  },
95
95
  });
96
+ // Hand the committed record to the manager so it reaches the Agent's live bus after
97
+ // the completion transaction commits, exactly like every other Agent-owned record.
98
+ context.onRecordAppended?.(appended);
96
99
  return Object.freeze({
97
100
  internalInferenceId: result.internalInferenceId,
98
101
  rootInternalInferenceId: context.attempt.rootId,
package/src/index.ts CHANGED
@@ -45,6 +45,12 @@ export type {
45
45
  OpenAgentConversationConfig,
46
46
  OpenOwnedAgentConversationResult,
47
47
  } from "./agent.ts";
48
+ export {
49
+ OUT_OF_BAND_MESSAGE_ORIGIN,
50
+ OUT_OF_BAND_PROMPT_MAX_CHARS,
51
+ isOutOfBandMessage,
52
+ } from "./out-of-band-messages.ts";
53
+ export type { AppendAssistantMessageInput } from "./out-of-band-messages.ts";
48
54
  export { AgentAdapterRegistry } from "./agent-adapter-registry.ts";
49
55
  export type { AgentAdapterRegistration } from "./agent-adapter-registry.ts";
50
56
  export { NoopAgentIdentityRuntime, composeIdentityPrompt } from "./identity.ts";
@@ -75,6 +81,17 @@ export {
75
81
  shouldCaptureProtocolMethod,
76
82
  searchableText,
77
83
  } from "./persistence/backend.ts";
84
+ export {
85
+ CONVERSATION_ERROR_CODES,
86
+ CONVERSATION_ERROR_RECOVERABILITIES,
87
+ CONVERSATION_ERROR_SOURCES,
88
+ buildConversationErrorDetails,
89
+ sanitizeConversationErrorMessage,
90
+ } from "./persistence/error-records.ts";
91
+ export type {
92
+ ConversationErrorCode,
93
+ ConversationErrorDetailInput,
94
+ } from "./persistence/error-records.ts";
78
95
  export {
79
96
  AgentDatabaseInUseError,
80
97
  SQLITE_AGENT_SCHEMA_VERSION,
@@ -96,6 +113,10 @@ export type {
96
113
  ConversationRecordCapturePolicy,
97
114
  ConversationRecordEnvelope,
98
115
  ConversationRecordKind,
116
+ ConversationErrorDetails,
117
+ ConversationErrorRecoverability,
118
+ ConversationErrorSource,
119
+ ErrorRecord,
99
120
  RecentRecordPage,
100
121
  RecentRecordPageOptions,
101
122
  IdentityMemoryObservation,
@@ -158,7 +179,9 @@ export {
158
179
  AdapterMismatchError,
159
180
  ContinuationUnavailableError,
160
181
  DirectAuditPersistenceUnsupportedError,
182
+ ProviderSessionError,
161
183
  } from "./agent-session.ts";
184
+ export type { ProviderSessionErrorDetails } from "./agent-session.ts";
162
185
  export type {
163
186
  AgentConversationConfig,
164
187
  AgentConversationOpenConfig,
@@ -530,6 +553,7 @@ export {
530
553
  UNAVAILABLE_PROVENANCE,
531
554
  } from "./metering/record.ts";
532
555
  export type {
556
+ AgentSessionHandoffErrorDetails,
533
557
  AgentSessionMeteringSnapshot,
534
558
  MeteredOperationKind,
535
559
  MeteringConfig,
@@ -2,7 +2,11 @@ import type { AgentConversationId, AgentSessionId } from "../agent-ids.ts";
2
2
  import type { AgentSessionMeteringState } from "../metering/state.ts";
3
3
  import type { OperationMeteringRecord, OperationOutcome } from "../metering/record.ts";
4
4
  import type { StatefulSubscribable, Subscribable } from "../observation/contracts.ts";
5
- import type { PersistenceJsonValue, PersistenceScope } from "../persistence/backend.ts";
5
+ import type {
6
+ ConversationRecord,
7
+ PersistenceJsonValue,
8
+ PersistenceScope,
9
+ } from "../persistence/backend.ts";
6
10
  import type { ResponseMessage, TokenUsage } from "../types.ts";
7
11
 
8
12
  export type InternalInferenceId = `aii-${string}`;
@@ -202,6 +206,13 @@ export interface InternalInferenceCompletionContext {
202
206
  /** Transaction-scoped persistence used to publish the purpose artifact atomically. */
203
207
  readonly persistence: PersistenceScope;
204
208
  readonly meteringState?: AgentSessionMeteringState;
209
+ /**
210
+ * Register a canonical record appended in this completion transaction for post-commit
211
+ * publication. The manager publishes it only after the transaction commits, so a
212
+ * rolled-back completion is never observed. Strategies that append no canonical record
213
+ * simply do not call it.
214
+ */
215
+ readonly onRecordAppended?: (record: ConversationRecord) => void;
205
216
  }
206
217
 
207
218
  export interface InternalInferenceStrategy<TPayload = PersistenceJsonValue> {
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import type { AgentSessionId } from "../../agent-ids.ts";
3
- import type { PersistenceBackend } from "../../persistence/backend.ts";
3
+ import type { ConversationRecord, PersistenceBackend } from "../../persistence/backend.ts";
4
4
  import type { OperationMeteringRecord } from "../../metering/record.ts";
5
5
  import { SubscriptionHub } from "../../observation/subscription-hub.ts";
6
6
  import { createInternalInferenceId } from "../ids.ts";
@@ -43,6 +43,13 @@ export interface DefaultInternalInferenceManagerConfig {
43
43
  ) => Promise<InternalInferenceMeteringOperation | null>;
44
44
  readonly meteringRecords?: import("../../persistence/backend.ts").MeteringRecordRetention;
45
45
  readonly pollIntervalMs?: number;
46
+ /**
47
+ * Observe canonical records appended by a strategy's completion, after the transaction
48
+ * that wrote them commits. The Agent uses this to publish internal-inference artifacts
49
+ * (such as conversation-checkpoint `native_action` records) through the same committed
50
+ * record stream as every other Agent-owned record.
51
+ */
52
+ readonly onCommittedRecords?: (records: readonly ConversationRecord[]) => void;
46
53
  }
47
54
 
48
55
  /** Agent-scoped durable scheduler. Purpose-specific artifact transactions remain strategies' responsibility. */
@@ -274,10 +281,14 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
274
281
  ? await openedMetering.close({ outcome: "completed", result })
275
282
  : null;
276
283
  if (this.fenced.has(attempt.internalInferenceId)) return;
284
+ // Canonical records a strategy appends here are buffered and published only after
285
+ // the transaction commits; a rollback must leave them unobserved.
286
+ const appended: ConversationRecord[] = [];
277
287
  const completed = await this.config.persistence.transaction(async (persistence) => {
278
288
  const completion = await strategy.complete({
279
289
  attempt: snapshotOf(attempt),
280
290
  persistence,
291
+ onRecordAppended: (record) => appended.push(record),
281
292
  }, result);
282
293
  if (this.fenced.has(attempt.internalInferenceId)) {
283
294
  throw new Error("internal inference was fenced during completion");
@@ -309,6 +320,7 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
309
320
  : {}),
310
321
  });
311
322
  });
323
+ if (appended.length > 0) this.config.onCommittedRecords?.(appended);
312
324
  this.publishAttempt(completed);
313
325
  await this.refreshRun(attempt.rootInternalInferenceId);
314
326
  await this.pruneTerminal();
@@ -905,6 +905,19 @@ export class MeteringEngine {
905
905
  * provider usage, and pretending otherwise would put a fabricated operation in the
906
906
  * consumer's ledger.
907
907
  */
908
+ /**
909
+ * Adopt totals accumulated by a parallel engine that is being discarded.
910
+ *
911
+ * A transition meters its target on its own engine, because the target's counters start
912
+ * at zero. When the transition fails, those operations were still minted, reported and
913
+ * paid for, so their totals belong to the session that remains. Unlike `reconcile` this
914
+ * is not a correction: nothing this engine measured was wrong, so its own baseline and
915
+ * any block it is under both stand.
916
+ */
917
+ adoptAccounting(state: AgentSessionMeteringState): void {
918
+ this.state = Object.freeze({ ...state, activeBaseline: this.state.activeBaseline });
919
+ }
920
+
908
921
  reconcile(state: AgentSessionMeteringState): { before: AgentSessionMeteringState } {
909
922
  const before = this.state;
910
923
  this.state = state;
@@ -9,7 +9,7 @@
9
9
  // to assert it cost zero, which is the difference between "we don't know" and a false
10
10
  // accounting entry.
11
11
 
12
- import type { TokenUsage } from "../types.ts";
12
+ import type { PromptResult, TokenUsage } from "../types.ts";
13
13
  import type { ContextWindowStatus, ProviderCostSnapshot } from "./context.ts";
14
14
  import type { Money } from "./money.ts";
15
15
  import type { AttributableUsage } from "./rating.ts";
@@ -261,18 +261,50 @@ export class AgentSessionOperationError extends Error {
261
261
  * A rejected handoff cannot return a HandoffResult, but the summary and seed prompts it
262
262
  * already ran consumed real tokens, so their records must still reach the caller.
263
263
  */
264
+ export interface AgentSessionHandoffErrorDetails {
265
+ readonly fromInternalSessionId?: string | null;
266
+ /** Present once the provider returned an id for the target. */
267
+ readonly toInternalSessionId?: string;
268
+ /** Local attachment state of the target, when one was created. */
269
+ readonly providerAttachment?: "runtime_only" | "recorded";
270
+ /** Whether the target became the recorded continuation before the failure. */
271
+ readonly activationCompleted?: boolean;
272
+ readonly summary?: string;
273
+ /** Result of `targetPrompt`, including a non-completed one that caused this failure. */
274
+ readonly targetResult?: PromptResult;
275
+ }
276
+
264
277
  export class AgentSessionHandoffError extends Error {
265
278
  readonly handoffId: string;
266
279
  readonly meteringRecords: readonly OperationMeteringRecord[];
280
+ readonly fromInternalSessionId: string | null;
281
+ readonly toInternalSessionId?: string;
282
+ readonly providerAttachment?: "runtime_only" | "recorded";
283
+ /**
284
+ * Distinguishes a target that never superseded the source from one that already did.
285
+ *
286
+ * A target prompt can fail after the target is the recorded continuation; that is an
287
+ * operation failure, not an activation rollback, and the two need different handling.
288
+ */
289
+ readonly activationCompleted: boolean;
290
+ readonly summary?: string;
291
+ readonly targetResult?: PromptResult;
267
292
 
268
293
  constructor(
269
294
  handoffId: string,
270
295
  meteringRecords: readonly OperationMeteringRecord[],
271
296
  cause: unknown,
297
+ details: AgentSessionHandoffErrorDetails = {},
272
298
  ) {
273
299
  super(cause instanceof Error ? cause.message : String(cause), { cause });
274
300
  this.name = "AgentSessionHandoffError";
275
301
  this.handoffId = handoffId;
276
302
  this.meteringRecords = Object.freeze([...meteringRecords]);
303
+ this.fromInternalSessionId = details.fromInternalSessionId ?? null;
304
+ if (details.toInternalSessionId !== undefined) this.toInternalSessionId = details.toInternalSessionId;
305
+ if (details.providerAttachment !== undefined) this.providerAttachment = details.providerAttachment;
306
+ this.activationCompleted = details.activationCompleted ?? false;
307
+ if (details.summary !== undefined) this.summary = details.summary;
308
+ if (details.targetResult !== undefined) this.targetResult = details.targetResult;
277
309
  }
278
310
  }
@@ -0,0 +1,154 @@
1
+ import type { AgentConversationId, AgentSessionId } from "../agent-ids.ts";
2
+ import {
3
+ isConversationRecordKind,
4
+ type ConversationRecord,
5
+ type ConversationRecordKind,
6
+ } from "../persistence/backend.ts";
7
+ import type { Subscribable, Unsubscribe } from "./contracts.ts";
8
+ import { SubscriptionHub, type SubscriptionListenerError } from "./subscription-hub.ts";
9
+
10
+ /** Declarative selection of committed records. Filters are fixed for one subscription. */
11
+ export interface AgentEventSubscriptionOptions {
12
+ /** Undefined means every Agent-owned conversation. An empty array selects nothing. */
13
+ readonly conversationIds?: readonly AgentConversationId[];
14
+ /** Undefined means every canonical conversation-record kind. An empty array selects nothing. */
15
+ readonly recordKinds?: readonly ConversationRecordKind[];
16
+ }
17
+
18
+ export interface ConversationRecordCommittedEvent {
19
+ readonly kind: "conversation_record_committed";
20
+ readonly record: ConversationRecord;
21
+ }
22
+
23
+ export type AgentEvent = ConversationRecordCommittedEvent;
24
+
25
+ export interface AgentEventNotification {
26
+ /** Process-local order assigned before subscriber filtering. Not a durable cursor. */
27
+ readonly deliverySequence: number;
28
+ /** Time at which the committed record was offered to listeners. */
29
+ readonly emittedAt: string;
30
+ readonly agentSessionId: AgentSessionId;
31
+ readonly event: AgentEvent;
32
+ }
33
+
34
+ export type AgentEventListener = (notification: AgentEventNotification) => void;
35
+
36
+ export interface AgentEventBus extends Subscribable<AgentEventNotification> {
37
+ subscribe(listener: AgentEventListener, options?: AgentEventSubscriptionOptions): Unsubscribe;
38
+ }
39
+
40
+ export interface AgentEventBusOptions {
41
+ readonly agentSessionId: AgentSessionId;
42
+ readonly onListenerError?: (failure: SubscriptionListenerError<AgentEventNotification>) => void;
43
+ }
44
+
45
+ type RecordFilter = (record: ConversationRecord) => boolean;
46
+
47
+ function compileFilter(options: AgentEventSubscriptionOptions): RecordFilter {
48
+ const conversationIds = compileConversationIds(options.conversationIds);
49
+ const recordKinds = compileRecordKinds(options.recordKinds);
50
+ return (record) =>
51
+ (conversationIds === null || conversationIds.has(record.agentConversationId))
52
+ && (recordKinds === null || recordKinds.has(record.kind));
53
+ }
54
+
55
+ function compileConversationIds(
56
+ ids: readonly AgentConversationId[] | undefined,
57
+ ): ReadonlySet<AgentConversationId> | null {
58
+ if (ids === undefined) return null;
59
+ if (!Array.isArray(ids)) {
60
+ throw new TypeError("agent event subscription conversationIds must be an array");
61
+ }
62
+ const normalized = new Set<AgentConversationId>();
63
+ for (const id of ids) {
64
+ if (typeof id !== "string" || id.trim() === "") {
65
+ throw new TypeError("agent event subscription conversationIds must contain non-blank strings");
66
+ }
67
+ normalized.add(id as AgentConversationId);
68
+ }
69
+ return normalized;
70
+ }
71
+
72
+ function compileRecordKinds(
73
+ kinds: readonly ConversationRecordKind[] | undefined,
74
+ ): ReadonlySet<ConversationRecordKind> | null {
75
+ if (kinds === undefined) return null;
76
+ if (!Array.isArray(kinds)) {
77
+ throw new TypeError("agent event subscription recordKinds must be an array");
78
+ }
79
+ const normalized = new Set<ConversationRecordKind>();
80
+ for (const kind of kinds) {
81
+ if (!isConversationRecordKind(kind)) {
82
+ throw new TypeError(`agent event subscription received an unknown record kind: ${String(kind)}`);
83
+ }
84
+ normalized.add(kind);
85
+ }
86
+ return normalized;
87
+ }
88
+
89
+ /**
90
+ * Process-local observation of committed canonical conversation records.
91
+ *
92
+ * Not durable, not replayable, and never a source of truth: SQLite remains authoritative.
93
+ * A record is published only after the transaction that appended it commits, and every
94
+ * physical append emits one notification, so evolving records produce one event per
95
+ * revision. Consumers reconcile those by canonical identity exactly as a reload would.
96
+ */
97
+ export class CommittedRecordEventBus implements AgentEventBus {
98
+ private readonly hub: SubscriptionHub<AgentEventNotification>;
99
+ private deliverySequence = 0;
100
+ private subscriptionCount = 0;
101
+ private closed = false;
102
+
103
+ constructor(private readonly options: AgentEventBusOptions) {
104
+ this.hub = new SubscriptionHub(options.onListenerError);
105
+ }
106
+
107
+ subscribe(listener: AgentEventListener, options: AgentEventSubscriptionOptions = {}): Unsubscribe {
108
+ if (typeof listener !== "function") {
109
+ throw new TypeError("agent event subscription listener must be a function");
110
+ }
111
+ const matches = compileFilter(options);
112
+ this.subscriptionCount += 1;
113
+ const unsubscribe = this.hub.subscribe((notification) => {
114
+ if (!matches(notification.event.record)) return;
115
+ listener(notification);
116
+ });
117
+ let subscribed = true;
118
+ return () => {
119
+ if (!subscribed) return;
120
+ subscribed = false;
121
+ this.subscriptionCount -= 1;
122
+ unsubscribe();
123
+ };
124
+ }
125
+
126
+ /** @internal Publish records whose persistence transaction has already committed. */
127
+ publish(records: readonly ConversationRecord[]): void {
128
+ // No subscribers means no notification to allocate; the delivery sequence is
129
+ // process-local and never a durable cursor, so skipping it is unobservable.
130
+ if (this.closed || this.subscriptionCount === 0 || records.length === 0) return;
131
+ const ordered = records.length > 1
132
+ ? [...records].sort((left, right) => left.sequence - right.sequence)
133
+ : records;
134
+ for (const record of ordered) {
135
+ const notification: AgentEventNotification = Object.freeze({
136
+ deliverySequence: (this.deliverySequence += 1),
137
+ emittedAt: new Date().toISOString(),
138
+ agentSessionId: this.options.agentSessionId,
139
+ event: Object.freeze({
140
+ kind: "conversation_record_committed" as const,
141
+ record,
142
+ }),
143
+ });
144
+ this.hub.emit(notification);
145
+ }
146
+ }
147
+
148
+ /** @internal Prevent further publication and drop every subscription. */
149
+ close(): void {
150
+ this.closed = true;
151
+ this.subscriptionCount = 0;
152
+ this.hub.clear();
153
+ }
154
+ }
@@ -6,3 +6,11 @@ export type {
6
6
  } from "./contracts.ts";
7
7
  export { SubscriptionHub } from "./subscription-hub.ts";
8
8
  export type { SubscriptionListenerError } from "./subscription-hub.ts";
9
+ export type {
10
+ AgentEvent,
11
+ AgentEventBus,
12
+ AgentEventListener,
13
+ AgentEventNotification,
14
+ AgentEventSubscriptionOptions,
15
+ ConversationRecordCommittedEvent,
16
+ } from "./agent-event-bus.ts";
@@ -0,0 +1,187 @@
1
+ import type { AgentConversationId } from "./agent-ids.ts";
2
+ import type {
3
+ ConversationRecord,
4
+ MessageRecord,
5
+ PersistenceBackend,
6
+ PersistenceJsonValue,
7
+ } from "./persistence/backend.ts";
8
+
9
+ /** Input for an assistant message a consumer appends without running a provider turn. */
10
+ export interface AppendAssistantMessageInput {
11
+ readonly text: string;
12
+ /** Opaque JSON stored on the record for the consumer's own use. */
13
+ readonly consumerMetadata?: PersistenceJsonValue;
14
+ }
15
+
16
+ /** Record `metadata.origin` marking an assistant message the provider did not produce. */
17
+ export const OUT_OF_BAND_MESSAGE_ORIGIN = "out_of_band";
18
+
19
+ /** Upper bound on the provider-only block; older messages are dropped first. */
20
+ export const OUT_OF_BAND_PROMPT_MAX_CHARS = 8_000;
21
+
22
+ const RECENT_PAGE_SIZE = 50;
23
+
24
+ export function isOutOfBandMessage(record: ConversationRecord): record is MessageRecord {
25
+ return record.kind === "message" && parseMetadata(record.metadata).origin === OUT_OF_BAND_MESSAGE_ORIGIN;
26
+ }
27
+
28
+ /**
29
+ * Out-of-band assistant messages the provider context has not received yet.
30
+ *
31
+ * Everything appended before the user record of the last completed turn was composed into
32
+ * that turn's provider text, and a recovery seed carries every canonical message through
33
+ * `recoveredThroughSequence`. So the window starts after the later of those two points and
34
+ * ends before the current user record, which must already be persisted: an append that
35
+ * races this read lands either inside the window or after the current user record.
36
+ */
37
+ export async function pendingOutOfBandMessages(
38
+ persistence: PersistenceBackend,
39
+ conversationId: AgentConversationId,
40
+ targetProviderContextId: string | undefined,
41
+ currentUserSequence: number,
42
+ ): Promise<readonly MessageRecord[]> {
43
+ const watermark = Math.max(
44
+ await recoveredThroughSequence(persistence, conversationId, targetProviderContextId),
45
+ await lastCompletedTurnUserSequence(persistence, conversationId, currentUserSequence),
46
+ );
47
+ if (watermark >= currentUserSequence - 1) return [];
48
+ const pending: MessageRecord[] = [];
49
+ let cursor: string | undefined;
50
+ do {
51
+ const page = await persistence.messages.list(conversationId, {
52
+ afterSequence: watermark,
53
+ throughSequence: currentUserSequence - 1,
54
+ limit: 500,
55
+ ...(cursor ? { cursor } : {}),
56
+ });
57
+ for (const message of page.messages) {
58
+ if (message.role === "assistant" && isOutOfBandMessage(message) && textOf(message)) {
59
+ pending.push(message);
60
+ }
61
+ }
62
+ cursor = page.nextCursor;
63
+ } while (cursor);
64
+ return pending;
65
+ }
66
+
67
+ /**
68
+ * Provider text for one turn: identity preamble, then out-of-band messages, then the user's
69
+ * own text. Only the user's text is persisted; everything else reaches the provider alone.
70
+ */
71
+ export function composeProviderPrompt(
72
+ prompt: string,
73
+ identityPreamble: string | undefined,
74
+ outOfBand: readonly MessageRecord[],
75
+ ): string {
76
+ const sections = [identityPreamble?.trim(), formatOutOfBandBlock(outOfBand)]
77
+ .filter((section): section is string => Boolean(section));
78
+ if (sections.length === 0) return prompt;
79
+ return `${sections.join("\n\n")}\n\n<current-message>\n${prompt}\n</current-message>`;
80
+ }
81
+
82
+ function formatOutOfBandBlock(messages: readonly MessageRecord[]): string | undefined {
83
+ if (messages.length === 0) return undefined;
84
+ const header = "Messages you sent in this conversation through another channel since your last turn."
85
+ + " The user has seen them; you have not.";
86
+ const entries = messages.map((message) => `[${message.timestamp}] ${textOf(message)}`);
87
+ let budget = OUT_OF_BAND_PROMPT_MAX_CHARS - header.length;
88
+ let kept = 0;
89
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
90
+ const cost = entries[index]!.length + 1;
91
+ if (cost > budget && kept > 0) break;
92
+ budget -= cost;
93
+ kept += 1;
94
+ }
95
+ const omitted = entries.length - kept;
96
+ const body = [
97
+ ...(omitted > 0 ? [`(${omitted} earlier message${omitted === 1 ? "" : "s"} omitted)`] : []),
98
+ ...entries.slice(omitted),
99
+ ];
100
+ return `<messages-you-sent>\n${header}\n${body.join("\n")}\n</messages-you-sent>`;
101
+ }
102
+
103
+ async function recoveredThroughSequence(
104
+ persistence: PersistenceBackend,
105
+ conversationId: AgentConversationId,
106
+ targetProviderContextId: string | undefined,
107
+ ): Promise<number> {
108
+ if (!targetProviderContextId) return 0;
109
+ const active = await persistence.providerSessions.active(conversationId);
110
+ if (active?.internalSessionId !== targetProviderContextId) return 0;
111
+ const value = parseMetadata(active.metadata).recoveredThroughSequence;
112
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
113
+ }
114
+
115
+ /** Sequence of the user record whose turn most recently completed, or 0 when none did. */
116
+ async function lastCompletedTurnUserSequence(
117
+ persistence: PersistenceBackend,
118
+ conversationId: AgentConversationId,
119
+ beforeSequence: number,
120
+ ): Promise<number> {
121
+ const records = persistence.records;
122
+ if (records.listRecent) {
123
+ let olderCursor: string | undefined;
124
+ do {
125
+ const page = await records.listRecent(conversationId, {
126
+ kinds: ["message"],
127
+ limit: RECENT_PAGE_SIZE,
128
+ ...(olderCursor ? { olderCursor } : {}),
129
+ });
130
+ for (let index = page.records.length - 1; index >= 0; index -= 1) {
131
+ const found = await completedTurnUserSequence(persistence, page.records[index]!, beforeSequence);
132
+ if (found !== undefined) return found;
133
+ }
134
+ olderCursor = page.olderCursor;
135
+ } while (olderCursor);
136
+ return 0;
137
+ }
138
+ // Custom backends without newest-first history pay a forward scan.
139
+ let latest = 0;
140
+ let cursor: string | undefined;
141
+ do {
142
+ const page = await records.list(conversationId, {
143
+ kinds: ["message"],
144
+ throughSequence: beforeSequence - 1,
145
+ ...(cursor ? { cursor } : {}),
146
+ });
147
+ for (const record of page.records) {
148
+ const found = await completedTurnUserSequence(persistence, record, beforeSequence);
149
+ if (found !== undefined) latest = Math.max(latest, found);
150
+ }
151
+ cursor = page.nextCursor;
152
+ } while (cursor);
153
+ return latest;
154
+ }
155
+
156
+ async function completedTurnUserSequence(
157
+ persistence: PersistenceBackend,
158
+ record: ConversationRecord,
159
+ beforeSequence: number,
160
+ ): Promise<number | undefined> {
161
+ if (record.kind !== "message" || record.sequence >= beforeSequence) return undefined;
162
+ if (record.role !== "assistant" || record.status !== "completed") return undefined;
163
+ const metadata = parseMetadata(record.metadata);
164
+ if (metadata.origin === OUT_OF_BAND_MESSAGE_ORIGIN) return undefined;
165
+ const operationId = metadata.operationId;
166
+ if (typeof operationId !== "string" || !operationId) return undefined;
167
+ const user = await persistence.records.get(`${operationId}:user`);
168
+ return user && user.sequence < beforeSequence ? user.sequence : undefined;
169
+ }
170
+
171
+ function textOf(message: MessageRecord): string {
172
+ if (typeof message.content === "string") return message.content.trim();
173
+ return message.content
174
+ .map((block) => block.type === "text" ? block.text : "")
175
+ .join("")
176
+ .trim();
177
+ }
178
+
179
+ function parseMetadata(metadata: string | undefined): Record<string, unknown> {
180
+ if (!metadata) return {};
181
+ try {
182
+ const value: unknown = JSON.parse(metadata);
183
+ return typeof value === "object" && value !== null ? value as Record<string, unknown> : {};
184
+ } catch {
185
+ return {};
186
+ }
187
+ }