@qlairoslabs/acp-client 0.7.4 → 0.8.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 (53) hide show
  1. package/CHANGELOG-audit.md +58 -0
  2. package/CONSUMER_GUIDE.md +452 -19
  3. package/package.json +6 -1
  4. package/src/agent-adapter-registry.ts +66 -0
  5. package/src/agent-conversation-continuation.ts +121 -0
  6. package/src/agent-conversation-contracts.ts +279 -0
  7. package/src/agent-conversation-errors.ts +31 -0
  8. package/src/agent-conversation-owner.ts +55 -0
  9. package/src/agent-conversation-presentation.ts +217 -0
  10. package/src/agent-conversation-queue.ts +44 -0
  11. package/src/agent-conversation.ts +41 -0
  12. package/src/agent-ids.ts +50 -0
  13. package/src/agent-session.ts +973 -673
  14. package/src/agent.ts +1175 -0
  15. package/src/audit/config.ts +186 -0
  16. package/src/audit/contracts.ts +59 -0
  17. package/src/audit/index.ts +50 -0
  18. package/src/audit/projection.ts +125 -0
  19. package/src/audit/reader.ts +371 -0
  20. package/src/audit/runtime.ts +1060 -0
  21. package/src/checkpointing/config.ts +91 -0
  22. package/src/checkpointing/contracts.ts +45 -0
  23. package/src/checkpointing/coordinator.ts +100 -0
  24. package/src/checkpointing/ids.ts +5 -0
  25. package/src/checkpointing/index.ts +6 -0
  26. package/src/checkpointing/persistence/sqlite-repository.ts +159 -0
  27. package/src/checkpointing/recovery.ts +114 -0
  28. package/src/checkpointing/strategy.ts +139 -0
  29. package/src/identity.ts +62 -0
  30. package/src/index.ts +117 -0
  31. package/src/internal-inference/config.ts +68 -0
  32. package/src/internal-inference/contracts.ts +218 -0
  33. package/src/internal-inference/coordination/handles.ts +133 -0
  34. package/src/internal-inference/coordination/manager.ts +487 -0
  35. package/src/internal-inference/ids.ts +10 -0
  36. package/src/internal-inference/index.ts +10 -0
  37. package/src/internal-inference/persistence/records.ts +132 -0
  38. package/src/internal-inference/persistence/repository.ts +35 -0
  39. package/src/internal-inference/persistence/sqlite-repository.ts +551 -0
  40. package/src/internal-inference/runtime/harness-runtime.ts +78 -0
  41. package/src/internal-inference/strategy/registry.ts +42 -0
  42. package/src/metering/engine.ts +47 -0
  43. package/src/metering/record.ts +4 -1
  44. package/src/observation/contracts.ts +10 -0
  45. package/src/observation/index.ts +8 -0
  46. package/src/observation/subscription-hub.ts +43 -0
  47. package/src/persistence/activity-projection.ts +26 -12
  48. package/src/persistence/backend.ts +774 -0
  49. package/src/persistence/index.ts +99 -0
  50. package/src/persistence/sqlite-backend.ts +1927 -0
  51. package/src/persistence/sqlite-conversation-records.ts +425 -0
  52. package/src/persistence/sqlite-owner-lock.ts +106 -0
  53. package/src/persistence/sqlite-schema.ts +561 -0
@@ -0,0 +1,121 @@
1
+ import type {
2
+ ContinuationAttempt,
3
+ ContinuationReport,
4
+ ContinuationStrategy,
5
+ OpenContinuationOptions,
6
+ } from "./agent-conversation-contracts.ts";
7
+ import type { AgentSessionCheckpoint } from "./persistence/checkpoint.ts";
8
+ import type { InternalSessionDescriptor } from "./persistence/records.ts";
9
+ import type { StagedContinuationState } from "./persistence/registry.ts";
10
+ import type { PersistenceStateRuntime } from "./persistence/state-runtime.ts";
11
+
12
+ export const HANDOFF_SUMMARY_PROMPT = [
13
+ "Create portable continuation context for a new agent thread.",
14
+ "Summarize the objective, decisions, completed work, current state, important files or identifiers,",
15
+ "and concrete next steps. Preserve unresolved risks and constraints. Return only the continuation context.",
16
+ ].join(" ");
17
+
18
+ export function buildContinuationPrompt(summary: string): string {
19
+ return [
20
+ "Continue this conversation using the following portable continuation context.",
21
+ "Treat it as prior context, not as a new user request. Confirm internally and continue from this state.",
22
+ "",
23
+ summary,
24
+ ].join("\n");
25
+ }
26
+
27
+ export function isReconstructionStrategy(strategy: ContinuationStrategy): boolean {
28
+ return strategy.kind === "new_from_transcript" || strategy.kind === "new_from_consumer_continuation";
29
+ }
30
+
31
+ /** Validate and take an immutable snapshot of caller-supplied continuation policy. */
32
+ export function normalizeContinuationStrategies(
33
+ options: OpenContinuationOptions | undefined,
34
+ ): readonly ContinuationStrategy[] {
35
+ const strategies = options?.strategies ?? [{ kind: "load_internal_session" as const }];
36
+ if (strategies.length === 0) throw new Error("continuation.strategies cannot be empty");
37
+ return Object.freeze(strategies.map((strategy): ContinuationStrategy => {
38
+ if (strategy.kind === "load_internal_session") {
39
+ return Object.freeze({ kind: strategy.kind });
40
+ }
41
+ if (strategy.kind === "new_from_transcript") {
42
+ if (!strategy.strategyId.trim()) throw new Error("transcript continuation strategyId cannot be blank");
43
+ if (typeof strategy.buildContinuation !== "function") {
44
+ throw new Error("transcript continuation strategy requires buildContinuation");
45
+ }
46
+ return Object.freeze({
47
+ kind: strategy.kind,
48
+ strategyId: strategy.strategyId,
49
+ buildContinuation: strategy.buildContinuation,
50
+ });
51
+ }
52
+ if (!strategy.continuationId.trim()) throw new Error("consumer continuationId cannot be blank");
53
+ if (!strategy.continuation.trim()) throw new Error("consumer continuation cannot be blank");
54
+ return Object.freeze({
55
+ kind: strategy.kind,
56
+ continuationId: strategy.continuationId,
57
+ continuation: strategy.continuation,
58
+ });
59
+ }));
60
+ }
61
+
62
+ export function createContinuationReport(
63
+ checkpoint: AgentSessionCheckpoint,
64
+ requestedAdapterId: string,
65
+ transcript: Pick<PersistenceStateRuntime, "conversationAvailability">,
66
+ recordedThreadAvailability: ContinuationReport["recordedThreadAvailability"],
67
+ attempts: readonly ContinuationAttempt[],
68
+ outcome: ContinuationReport["outcome"],
69
+ ): ContinuationReport {
70
+ return Object.freeze({
71
+ recordedAdapterId: checkpoint.adapterId,
72
+ recordedInternalSessionId: checkpoint.internalSessionId,
73
+ requestedAdapterId,
74
+ recordedConversationAvailability: transcript.conversationAvailability,
75
+ recordedThreadAvailability,
76
+ attempts: Object.freeze(attempts.map((attempt) => Object.freeze({ ...attempt }))),
77
+ outcome: Object.freeze({ ...outcome }),
78
+ });
79
+ }
80
+
81
+ export function descriptorFromCheckpoint(
82
+ checkpoint: AgentSessionCheckpoint,
83
+ ): InternalSessionDescriptor {
84
+ return {
85
+ internalSessionId: checkpoint.internalSessionId,
86
+ adapterId: checkpoint.adapterId,
87
+ mode: checkpoint.mode,
88
+ model: checkpoint.model,
89
+ sessionConfiguration: checkpoint.sessionConfiguration,
90
+ activatedAt: checkpoint.internalSessionActivatedAt,
91
+ protocol: checkpoint.protocol,
92
+ };
93
+ }
94
+
95
+ /**
96
+ * Persist and verify the provider identity acquired while opening. This is kept outside
97
+ * the harness acquisition loop so storage coordination does not become controller logic.
98
+ */
99
+ export async function stageOpeningContinuation(
100
+ stage: ((state: StagedContinuationState) => Promise<StagedContinuationState>) | undefined,
101
+ checkpoint: AgentSessionCheckpoint,
102
+ internalSessionId: string,
103
+ ): Promise<void> {
104
+ if (!stage) return;
105
+ const observed: StagedContinuationState = {
106
+ adapterId: checkpoint.adapterId,
107
+ mode: checkpoint.mode,
108
+ internalSessionId,
109
+ internalSessionActivatedAt: checkpoint.internalSessionActivatedAt,
110
+ model: checkpoint.model,
111
+ sessionConfiguration: checkpoint.sessionConfiguration,
112
+ protocol: checkpoint.protocol,
113
+ };
114
+ const persisted = await stage(observed);
115
+ if (persisted.adapterId !== observed.adapterId
116
+ || persisted.mode !== observed.mode
117
+ || persisted.internalSessionId !== observed.internalSessionId) {
118
+ throw new Error("staged continuation disagrees with the loaded provider identity");
119
+ }
120
+ }
121
+
@@ -0,0 +1,279 @@
1
+ import type { AgentMode } from "./controller.ts";
2
+ import type { Adapter } from "./adapters.ts";
3
+ import type { ContextWindowStatus, ProviderCostSnapshot } from "./metering/context.ts";
4
+ import type { OperationMeteringRecord } from "./metering/record.ts";
5
+ import type { AgentSessionMeteringState } from "./metering/state.ts";
6
+ import type { AgentSessionCheckpoint, JsonValue } from "./persistence/checkpoint.ts";
7
+ import type { PersistedMachineCode } from "./persistence/integrity.ts";
8
+ import type { TranscriptPresentationItem } from "./persistence/presentation.ts";
9
+ import type { SessionRecoveryStatus } from "./persistence/reducer.ts";
10
+ import type { TranscriptReader } from "./persistence/transcript-reader.ts";
11
+ import type {
12
+ ActivityEvent,
13
+ InternalSessionCommand,
14
+ PromptResult,
15
+ } from "./types.ts";
16
+
17
+ /** What the current durable conversation implementation is doing right now. */
18
+ export type AgentSessionPhase =
19
+ | "idle"
20
+ | "prompting"
21
+ | "handoff"
22
+ | "configuring"
23
+ | "recovering"
24
+ | "switching_mode"
25
+ | "stopped";
26
+
27
+ /** Authoritative, immutable point-in-time state for orchestration consumers. */
28
+ export interface AgentSessionState {
29
+ readonly phase: AgentSessionPhase;
30
+ /** True only while an operation is executing; queued work is reported separately. */
31
+ readonly isBusy: boolean;
32
+ /** Operations waiting behind the active one. Does not count the active operation. */
33
+ readonly queuedOperationCount: number;
34
+ readonly agentSessionId: string;
35
+ readonly internalSessionId: string | null;
36
+ readonly adapterId: string;
37
+ readonly mode: AgentMode;
38
+ readonly promptability: AgentSessionPromptability;
39
+ }
40
+
41
+ export type ConfigurationRestoreStatus =
42
+ | { readonly kind: "matched" }
43
+ | { readonly kind: "partial"; readonly omittedConfigIds: readonly string[] }
44
+ | {
45
+ readonly kind: "mismatch";
46
+ readonly configIds: readonly string[];
47
+ readonly reasons: readonly string[];
48
+ };
49
+
50
+ export type PromptBlocker =
51
+ | "continuation_unavailable"
52
+ | "recovery_required"
53
+ | "configuration_mismatch"
54
+ | "persistence_unhealthy"
55
+ | "maintenance_pending"
56
+ | "session_stopped";
57
+
58
+ export type AgentSessionPromptability =
59
+ | { readonly promptable: true; readonly blockers: readonly [] }
60
+ | { readonly promptable: false; readonly blockers: readonly PromptBlocker[] };
61
+
62
+ export interface ContinuationAttempt {
63
+ readonly strategy: ContinuationStrategy["kind"];
64
+ readonly status: "succeeded" | "failed" | "skipped";
65
+ readonly errorCode?: PersistedMachineCode;
66
+ readonly reason?: string;
67
+ }
68
+
69
+ export interface ContinuationReport {
70
+ readonly recordedAdapterId: string;
71
+ readonly recordedInternalSessionId: string | null;
72
+ readonly requestedAdapterId: string;
73
+ readonly recordedConversationAvailability: "available" | "partial" | "not_captured";
74
+ readonly recordedThreadAvailability: "available" | "unavailable" | "not_checked";
75
+ readonly attempts: readonly ContinuationAttempt[];
76
+ readonly outcome:
77
+ | { readonly kind: "loaded"; readonly activeInternalSessionId: string }
78
+ | {
79
+ readonly kind: "reconstructed";
80
+ readonly source: "transcript" | "consumer";
81
+ readonly activeInternalSessionId: string;
82
+ readonly transitionId: string;
83
+ }
84
+ | { readonly kind: "unavailable" };
85
+ }
86
+
87
+ export interface TranscriptContinuationBuilderContext {
88
+ readonly agentSessionId: string;
89
+ readonly checkpoint: AgentSessionCheckpoint;
90
+ /** Snapshot-bound access to captured history; the builder decides how much to read. */
91
+ readonly transcript: TranscriptReader;
92
+ readonly targetAdapterId: string;
93
+ }
94
+
95
+ export type TranscriptContinuationBuilder = (
96
+ context: TranscriptContinuationBuilderContext,
97
+ ) => Promise<{ readonly continuation: string; readonly metadata?: Readonly<Record<string, JsonValue>> }>;
98
+
99
+ export type ContinuationStrategy =
100
+ | { readonly kind: "load_internal_session" }
101
+ | {
102
+ readonly kind: "new_from_transcript";
103
+ readonly strategyId: string;
104
+ readonly buildContinuation: TranscriptContinuationBuilder;
105
+ }
106
+ | {
107
+ readonly kind: "new_from_consumer_continuation";
108
+ readonly continuationId: string;
109
+ readonly continuation: string;
110
+ };
111
+
112
+ export interface OpenContinuationOptions {
113
+ /** Defaults to only `load_internal_session`; an empty array is invalid. */
114
+ readonly strategies?: readonly ContinuationStrategy[];
115
+ }
116
+
117
+ export type ConfigurationMismatchResolution =
118
+ | { readonly strategy: "accept_effective" }
119
+ | {
120
+ readonly strategy: "replace_restoration_targets";
121
+ readonly selections: readonly { readonly configId: string; readonly value: JsonValue }[];
122
+ };
123
+
124
+ export interface ConfigurationMismatchResolutionResult {
125
+ readonly configuration: ConfigurationRestoreStatus;
126
+ readonly appliedConfigIds: readonly string[];
127
+ }
128
+
129
+ export type AgentSessionRecoveryResolution =
130
+ | { readonly strategy: "accept_harness_state" }
131
+ | {
132
+ readonly strategy: "start_new_internal_session";
133
+ /** When omitted, the currently loaded harness thread generates portable context. */
134
+ readonly continuation?: string;
135
+ };
136
+
137
+ export interface AgentSessionRecoveryResolutionResult {
138
+ readonly previous: Extract<SessionRecoveryStatus, { readonly kind: "uncertain" }>;
139
+ readonly recovery: Extract<SessionRecoveryStatus, { readonly kind: "clean" }>;
140
+ /** Present when resolution deliberately replaced the provider thread. */
141
+ readonly handoff?: HandoffResult;
142
+ }
143
+
144
+ export interface HandoffOptions {
145
+ /** @deprecated Shorthand for `continuation: { kind: "provided", content: summary }`. */
146
+ readonly summary?: string;
147
+ /** Target provider. Omitted means a fresh thread on the current adapter and mode. */
148
+ readonly target?: {
149
+ readonly adapterId: string;
150
+ /** Explicit route for a detached conversation that has no owning Agent registry. */
151
+ readonly adapter?: Adapter;
152
+ readonly mode?: AgentMode;
153
+ readonly config?: Readonly<Record<string, unknown>>;
154
+ };
155
+ /** How portable context is produced. Defaults to a generated summary. */
156
+ readonly continuation?:
157
+ | {
158
+ readonly kind: "generated";
159
+ /** Appended to the library's summary prompt. */
160
+ readonly summaryInstructions?: string;
161
+ /** Replaces the library's summary prompt entirely. */
162
+ readonly summaryPrompt?: string;
163
+ }
164
+ | { readonly kind: "provided"; readonly content: string }
165
+ | { readonly kind: "none" };
166
+ /** Optional first instruction sent after continuation context has been installed. */
167
+ readonly targetPrompt?: string;
168
+ }
169
+
170
+ export interface HandoffResult {
171
+ readonly handoffId: string;
172
+ readonly agentSessionId: string;
173
+ readonly fromInternalSessionId: string | null;
174
+ readonly toInternalSessionId: string;
175
+ /** Present when the handoff crossed adapter routes. */
176
+ readonly fromAdapterId?: string;
177
+ /** Present when the handoff crossed adapter routes. */
178
+ readonly toAdapterId?: string;
179
+ readonly summary: string;
180
+ /** Result of `targetPrompt`, when one was supplied. */
181
+ readonly targetResult?: PromptResult;
182
+ /** One record per token-consuming operation the handoff performed, in order. */
183
+ readonly meteringRecords: readonly OperationMeteringRecord[];
184
+ }
185
+
186
+ /** Conversation-owned lifecycle events. Harness activity remains in PromptHandlers.onActivity. */
187
+ export type AgentSessionEvent =
188
+ | { kind: "state_changed"; state: AgentSessionState }
189
+ | { kind: "turn_started"; turnId: string }
190
+ | { kind: "turn_completed"; turnId: string; result: PromptResult }
191
+ | { kind: "turn_failed"; turnId: string; error: string }
192
+ | { kind: "presentation_recorded"; item: TranscriptPresentationItem }
193
+ | { kind: "internal_session_commands_changed"; commands: readonly InternalSessionCommand[] }
194
+ | { kind: "handoff_started"; handoffId: string; fromInternalSessionId: string | null }
195
+ | { kind: "handoff_completed"; result: HandoffResult }
196
+ | {
197
+ kind: "handoff_failed";
198
+ handoffId: string;
199
+ fromInternalSessionId: string | null;
200
+ toInternalSessionId?: string;
201
+ error: string;
202
+ meteringRecords: readonly OperationMeteringRecord[];
203
+ }
204
+ | { kind: "configuration_started"; operationId: string; configId: string }
205
+ | { kind: "configuration_completed"; operationId: string; configId: string }
206
+ | { kind: "configuration_failed"; operationId: string; configId: string; error: string }
207
+ | { kind: "mode_change_started"; transitionId: string; from: AgentMode; to: AgentMode }
208
+ | { kind: "mode_change_completed"; transitionId: string; from: AgentMode; to: AgentMode }
209
+ | { kind: "mode_change_failed"; transitionId: string; from: AgentMode; to: AgentMode; error: string }
210
+ | {
211
+ kind: "configuration_mismatch_resolved";
212
+ configuration: ConfigurationRestoreStatus;
213
+ appliedConfigIds: readonly string[];
214
+ }
215
+ | {
216
+ kind: "recovery_resolved";
217
+ strategy: AgentSessionRecoveryResolution["strategy"];
218
+ previous: Extract<SessionRecoveryStatus, { kind: "uncertain" }>;
219
+ recovery: Extract<SessionRecoveryStatus, { kind: "clean" }>;
220
+ }
221
+ | { kind: "context_window_changed"; contextWindow: ContextWindowStatus | null }
222
+ | { kind: "provider_cost_changed"; providerCost: ProviderCostSnapshot | null }
223
+ | { kind: "metering_recorded"; record: OperationMeteringRecord }
224
+ | { kind: "metering_blocked"; reason: string }
225
+ | { kind: "metering_unblocked" }
226
+ | {
227
+ kind: "metering_reconciled";
228
+ before: AgentSessionMeteringState;
229
+ after: AgentSessionMeteringState;
230
+ reason: string;
231
+ reference?: string;
232
+ reconciledAt: number;
233
+ };
234
+
235
+ /** A prompt result enriched with the operation's metering record. */
236
+ export interface AgentSessionPromptResult extends PromptResult {
237
+ readonly operationId: string;
238
+ /** Null only when a queued prompt was cancelled before provider dispatch. */
239
+ readonly metering: OperationMeteringRecord | null;
240
+ }
241
+
242
+ /** Ordered envelope delivered to every current AgentSession subscriber. */
243
+ export interface AgentSessionNotification {
244
+ readonly seq: number;
245
+ readonly ts: number;
246
+ readonly agentSessionId: string;
247
+ readonly event: AgentSessionEvent;
248
+ }
249
+
250
+ export type AgentSessionListener = (notification: AgentSessionNotification) => void;
251
+
252
+ /** Conversation-first names. The AgentSession forms remain compatibility aliases. */
253
+ export type AgentConversationPhase = AgentSessionPhase;
254
+ export type AgentConversationState = AgentSessionState;
255
+ export type AgentConversationPromptability = AgentSessionPromptability;
256
+ export type AgentConversationPromptResult = AgentSessionPromptResult;
257
+ export type AgentConversationEvent = AgentSessionEvent;
258
+ export type AgentConversationNotification = AgentSessionNotification;
259
+ export type AgentConversationListener = AgentSessionListener;
260
+ export type AgentConversationRecoveryResolution = AgentSessionRecoveryResolution;
261
+ export type AgentConversationRecoveryResolutionResult = AgentSessionRecoveryResolutionResult;
262
+
263
+ /** What to record when transcript activity capture is on. */
264
+ export interface TranscriptActivityConfig {
265
+ kinds?: Array<ActivityEvent["kind"]>;
266
+ checkpointOnInput?: boolean;
267
+ rawOutput?: boolean;
268
+ maxBytes?: number;
269
+ }
270
+
271
+ /** Explicit selection of the provider thread backing a newly opened conversation. */
272
+ export type ProviderSession =
273
+ | { readonly kind: "new" }
274
+ | {
275
+ readonly kind: "load";
276
+ readonly internalSessionId: string;
277
+ /** Default "error": never silently replace a requested thread. */
278
+ readonly onFailure?: "error" | "new";
279
+ };
@@ -0,0 +1,31 @@
1
+ import type { ContinuationReport, PromptBlocker } from "./agent-conversation-contracts.ts";
2
+
3
+ export class AgentSessionPromptBlockedError extends Error {
4
+ constructor(readonly blockers: readonly PromptBlocker[]) {
5
+ super(`AgentSession cannot mutate while blocked: ${blockers.join(", ")}`);
6
+ this.name = "AgentSessionPromptBlockedError";
7
+ }
8
+ }
9
+
10
+ export class ContinuationUnavailableError extends Error {
11
+ constructor(readonly continuation: ContinuationReport, options?: ErrorOptions) {
12
+ super("recorded internal session could not be loaded", options);
13
+ this.name = "ContinuationUnavailableError";
14
+ }
15
+ }
16
+
17
+ export class AdapterMismatchError extends Error {
18
+ constructor(readonly recordedAdapterId: string, readonly requestedAdapterId: string) {
19
+ super(`adapter mismatch: transcript requires ${recordedAdapterId}, received ${requestedAdapterId}`);
20
+ this.name = "AdapterMismatchError";
21
+ }
22
+ }
23
+
24
+ /** Direct V2 audit creation is deferred until it has the same crash transaction as managed creation. */
25
+ export class DirectAuditPersistenceUnsupportedError extends Error {
26
+ constructor() {
27
+ super("direct V2 audit persistence is not supported; use SessionManager.createAgentSession()");
28
+ this.name = "DirectAuditPersistenceUnsupportedError";
29
+ }
30
+ }
31
+
@@ -0,0 +1,55 @@
1
+ import type { AgentConversationId, AgentSessionId } from "./agent-ids.ts";
2
+ import type { Adapter } from "./adapters.ts";
3
+ import type { AgentMode } from "./controller.ts";
4
+ import type { NewConversationRecord, ParticipantRef } from "./persistence/backend.ts";
5
+ import type { AgentSessionPromptResult } from "./agent-conversation-contracts.ts";
6
+ import type { ResponseMessage } from "./types.ts";
7
+ import type { OperationMeteringRecord } from "./metering/record.ts";
8
+ import type { AgentSessionMeteringState } from "./metering/state.ts";
9
+
10
+ export interface OwnedPromptInput {
11
+ readonly operationId: string;
12
+ readonly agentSessionId: AgentSessionId;
13
+ readonly agentConversationId: AgentConversationId;
14
+ readonly participantId?: string;
15
+ readonly text: string;
16
+ }
17
+
18
+ export interface OwnedPromptPreparation {
19
+ readonly providerText?: string;
20
+ readonly participant?: ParticipantRef;
21
+ }
22
+
23
+ export interface OwnedPromptCompleted extends OwnedPromptInput {
24
+ readonly result: AgentSessionPromptResult;
25
+ }
26
+
27
+ export interface OwnedPromptFailed extends OwnedPromptInput {
28
+ readonly messages: readonly ResponseMessage[];
29
+ readonly error: unknown;
30
+ }
31
+
32
+ /** @internal Agent-owned persistence and identity boundary for a conversation turn. */
33
+ export interface AgentConversationOwnerLifecycle {
34
+ beforePrompt(input: OwnedPromptInput): Promise<OwnedPromptPreparation>;
35
+ afterPrompt(input: OwnedPromptCompleted): Promise<void>;
36
+ promptFailed(input: OwnedPromptFailed): Promise<void>;
37
+ /** Durably commit one normalized operation record and its bounded next state. */
38
+ meteringRecorded?(record: OperationMeteringRecord): Promise<void>;
39
+ /** Persist a bounded state change that did not itself mint an operation record. */
40
+ meteringStateChanged?(state: AgentSessionMeteringState): Promise<void>;
41
+ /** Resolve an agent-scoped route for a cross-adapter transition. */
42
+ resolveAdapter?(adapterId: string): Adapter;
43
+ /** Commit the newly active provider route before it becomes observable in memory. */
44
+ transitionActivated?(input: {
45
+ readonly transitionId: string;
46
+ readonly agentConversationId: AgentConversationId;
47
+ readonly internalSessionId: string;
48
+ readonly adapterId: string;
49
+ readonly mode: AgentMode;
50
+ readonly model?: string;
51
+ readonly activatedAt: string;
52
+ }): Promise<void>;
53
+ /** Append a typed non-message runtime observation under the owner's capture policy. */
54
+ record?(record: NewConversationRecord): Promise<void>;
55
+ }