@qlairoslabs/acp-client 0.7.3 → 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 (58) hide show
  1. package/CHANGELOG-audit.md +58 -0
  2. package/CONSUMER_GUIDE.md +474 -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 +1022 -682
  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/controller.ts +37 -5
  30. package/src/identity.ts +62 -0
  31. package/src/index.ts +121 -0
  32. package/src/internal-inference/config.ts +68 -0
  33. package/src/internal-inference/contracts.ts +218 -0
  34. package/src/internal-inference/coordination/handles.ts +133 -0
  35. package/src/internal-inference/coordination/manager.ts +487 -0
  36. package/src/internal-inference/ids.ts +10 -0
  37. package/src/internal-inference/index.ts +10 -0
  38. package/src/internal-inference/persistence/records.ts +132 -0
  39. package/src/internal-inference/persistence/repository.ts +35 -0
  40. package/src/internal-inference/persistence/sqlite-repository.ts +551 -0
  41. package/src/internal-inference/runtime/harness-runtime.ts +78 -0
  42. package/src/internal-inference/strategy/registry.ts +42 -0
  43. package/src/metering/engine.ts +47 -0
  44. package/src/metering/record.ts +4 -1
  45. package/src/observation/contracts.ts +10 -0
  46. package/src/observation/index.ts +8 -0
  47. package/src/observation/subscription-hub.ts +43 -0
  48. package/src/persistence/activity-projection.ts +26 -12
  49. package/src/persistence/backend.ts +774 -0
  50. package/src/persistence/index.ts +99 -0
  51. package/src/persistence/managed-creation.ts +18 -2
  52. package/src/persistence/managed-load.ts +19 -5
  53. package/src/persistence/managed-open-progress.ts +54 -0
  54. package/src/persistence/presentation.ts +3 -0
  55. package/src/persistence/sqlite-backend.ts +1927 -0
  56. package/src/persistence/sqlite-conversation-records.ts +425 -0
  57. package/src/persistence/sqlite-owner-lock.ts +106 -0
  58. package/src/persistence/sqlite-schema.ts +561 -0
package/src/controller.ts CHANGED
@@ -64,6 +64,15 @@ export interface AgentControllerConfig {
64
64
  wire?: (entry: WireEntry) => void;
65
65
  }
66
66
 
67
+ /** @internal Startup observations used by the managed AgentSession coordinator. */
68
+ export type AgentControllerStartEvent =
69
+ | { readonly stage: "initialized"; readonly capabilities: Capabilities }
70
+ | {
71
+ readonly stage: "internal_session_acquired";
72
+ readonly internalSessionId: string;
73
+ readonly disposition: "created" | "resumed";
74
+ };
75
+
67
76
  export type ControllerCommandId =
68
77
  | "caps"
69
78
  | "session"
@@ -177,11 +186,11 @@ export class AgentController implements AgentClient {
177
186
  return () => this.usageUpdateListeners.delete(listener);
178
187
  }
179
188
 
180
- async start(): Promise<ConnectResult> {
189
+ async start(onProgress?: (event: AgentControllerStartEvent) => void): Promise<ConnectResult> {
181
190
  if (this.current) {
182
191
  return { sessionId: this.currentSessionId ?? "", resumed: this.acp?.hasSession ?? false };
183
192
  }
184
- const brought = await this.bringUp(this.mode, this.config.sessionId);
193
+ const brought = await this.bringUp(this.mode, this.config.sessionId, onProgress);
185
194
  this.current = brought.client;
186
195
  this.acp = brought.acp;
187
196
  this.attachAvailableCommandSource();
@@ -189,12 +198,12 @@ export class AgentController implements AgentClient {
189
198
  }
190
199
 
191
200
  /** Explicitly create a fresh provider thread, ignoring any startup load target. */
192
- async startFresh(): Promise<ConnectResult> {
201
+ async startFresh(onProgress?: (event: AgentControllerStartEvent) => void): Promise<ConnectResult> {
193
202
  if (this.current) {
194
203
  if (!this.acp) throw new Error("fresh provider sessions require ACP normal mode");
195
204
  return await this.newSession();
196
205
  }
197
- const brought = await this.bringUp(this.mode);
206
+ const brought = await this.bringUp(this.mode, undefined, onProgress);
198
207
  this.current = brought.client;
199
208
  this.acp = brought.acp;
200
209
  this.attachAvailableCommandSource();
@@ -447,6 +456,7 @@ export class AgentController implements AgentClient {
447
456
  private async bringUp(
448
457
  mode: AgentMode,
449
458
  sessionId?: string,
459
+ onProgress?: (event: AgentControllerStartEvent) => void,
450
460
  ): Promise<{ client: AgentClient; acp: AcpClient | null; result: ConnectResult }> {
451
461
  const adapter = this.config.adapter;
452
462
  if (mode === "degraded") {
@@ -487,7 +497,8 @@ export class AgentController implements AgentClient {
487
497
  // unauthenticated agent may refuse session/new, but we keep the connection up so the
488
498
  // user can /login and then create a session. (Auth state is opaque — see SPEC.)
489
499
  try {
490
- await client.connect();
500
+ const capabilities = await client.connect();
501
+ this.reportStartProgress(onProgress, { stage: "initialized", capabilities });
491
502
  } catch (err) {
492
503
  await client.stop();
493
504
  throw err;
@@ -506,9 +517,30 @@ export class AgentController implements AgentClient {
506
517
  this.config.logger?.warn("session_start_failed", { error: String(err) });
507
518
  result = { sessionId: "", resumed: false };
508
519
  }
520
+ if (result.sessionId) {
521
+ this.reportStartProgress(onProgress, {
522
+ stage: "internal_session_acquired",
523
+ internalSessionId: result.sessionId,
524
+ disposition: result.resumed ? "resumed" : "created",
525
+ });
526
+ }
509
527
  return { client, acp: client, result };
510
528
  }
511
529
 
530
+ private reportStartProgress(
531
+ listener: ((event: AgentControllerStartEvent) => void) | undefined,
532
+ event: AgentControllerStartEvent,
533
+ ): void {
534
+ if (!listener) return;
535
+ try {
536
+ listener(event);
537
+ } catch (error) {
538
+ this.config.logger?.warn("controller_start_progress_listener_failed", {
539
+ error: String(error),
540
+ });
541
+ }
542
+ }
543
+
512
544
  private requireCurrent(): AgentClient {
513
545
  if (!this.current) throw new NotConnectedError("AgentController is not started — call start() first");
514
546
  return this.current;
@@ -0,0 +1,62 @@
1
+ import type { AgentConversationId, AgentSessionId } from "./agent-ids.ts";
2
+ import type { ConversationRecord, ParticipantRef, PersistenceJsonValue } from "./persistence/backend.ts";
3
+
4
+ export type IdentityConsistency = "eventual" | "through-current";
5
+
6
+ export interface IdentityLoadInput {
7
+ readonly agentSessionId: AgentSessionId;
8
+ readonly agentConversationId: AgentConversationId;
9
+ readonly participant?: ParticipantRef;
10
+ readonly prompt: string;
11
+ readonly consistency: IdentityConsistency;
12
+ readonly timeoutMs?: number;
13
+ }
14
+
15
+ export interface LoadedIdentityContext {
16
+ /** Optional private context prepended only to the provider prompt, never to chat history. */
17
+ readonly promptPreamble?: string;
18
+ readonly snapshotVersion?: number;
19
+ readonly observedThroughSequence?: number;
20
+ readonly processedThroughSequence?: number;
21
+ readonly metadata?: PersistenceJsonValue;
22
+ }
23
+
24
+ export interface IdentityUpdateInput {
25
+ readonly agentSessionId: AgentSessionId;
26
+ readonly agentConversationId: AgentConversationId;
27
+ readonly records: readonly ConversationRecord[];
28
+ }
29
+
30
+ export interface IdentitySynchronizationInput {
31
+ readonly agentSessionId: AgentSessionId;
32
+ readonly throughSequence: number;
33
+ readonly timeoutMs?: number;
34
+ }
35
+
36
+ export interface IdentityWatermark {
37
+ readonly observedThroughSequence: number;
38
+ readonly processedThroughSequence: number;
39
+ }
40
+
41
+ export interface AgentIdentityRuntime {
42
+ load(input: IdentityLoadInput): Promise<LoadedIdentityContext>;
43
+ update(input: IdentityUpdateInput): Promise<void>;
44
+ synchronize?(input: IdentitySynchronizationInput): Promise<IdentityWatermark>;
45
+ }
46
+
47
+ /** Default identity policy: deliberately remembers and injects nothing, but is still called. */
48
+ export class NoopAgentIdentityRuntime implements AgentIdentityRuntime {
49
+ async load(_input: IdentityLoadInput): Promise<LoadedIdentityContext> {
50
+ return EMPTY_IDENTITY_CONTEXT;
51
+ }
52
+
53
+ async update(_input: IdentityUpdateInput): Promise<void> {}
54
+ }
55
+
56
+ const EMPTY_IDENTITY_CONTEXT: LoadedIdentityContext = Object.freeze({});
57
+
58
+ export function composeIdentityPrompt(prompt: string, context: LoadedIdentityContext): string {
59
+ const preamble = context.promptPreamble?.trim();
60
+ if (!preamble) return prompt;
61
+ return `${preamble}\n\n<current-message>\n${prompt}\n</current-message>`;
62
+ }
package/src/index.ts CHANGED
@@ -17,6 +17,110 @@ export type {
17
17
 
18
18
  export type { AcpLauncher, PreparedLaunch, LaunchKind } from "./launcher.ts";
19
19
 
20
+ export {
21
+ AGENT_CONVERSATION_ID_PREFIX,
22
+ AGENT_SESSION_ID_PREFIX,
23
+ createAgentConversationId,
24
+ createAgentSessionId,
25
+ isAgentConversationId,
26
+ isAgentSessionId,
27
+ parseAgentConversationId,
28
+ parseAgentSessionId,
29
+ } from "./agent-ids.ts";
30
+ export type { AgentConversationId, AgentSessionId } from "./agent-ids.ts";
31
+ export * from "./observation/index.ts";
32
+ export * from "./internal-inference/index.ts";
33
+ export * from "./checkpointing/index.ts";
34
+ export * from "./audit/index.ts";
35
+
36
+ export { Agent } from "./agent.ts";
37
+ export type {
38
+ AgentConfig,
39
+ AgentConversationManager,
40
+ AgentConversationRuntimeDefaults,
41
+ AgentPersistenceConfig,
42
+ CreateAgentConversationConfig,
43
+ OpenAgentConversationConfig,
44
+ OpenOwnedAgentConversationResult,
45
+ } from "./agent.ts";
46
+ export { AgentAdapterRegistry } from "./agent-adapter-registry.ts";
47
+ export type { AgentAdapterRegistration } from "./agent-adapter-registry.ts";
48
+ export { NoopAgentIdentityRuntime, composeIdentityPrompt } from "./identity.ts";
49
+ export type {
50
+ AgentIdentityRuntime,
51
+ IdentityConsistency,
52
+ IdentityLoadInput,
53
+ IdentitySynchronizationInput,
54
+ IdentityUpdateInput,
55
+ IdentityWatermark,
56
+ LoadedIdentityContext,
57
+ } from "./identity.ts";
58
+
59
+ export {
60
+ CONVERSATION_RECORD_KINDS,
61
+ DEFAULT_CONVERSATION_RECORD_CAPTURE,
62
+ IMPLICIT_USER_PARTICIPANT_ID,
63
+ PARTICIPANT_KINDS,
64
+ PersistenceCapabilityError,
65
+ PersistenceConflictError,
66
+ isConversationRecordKind,
67
+ isParticipantKind,
68
+ normalizeParticipantRef,
69
+ resolveConversationRecordCapture,
70
+ shouldCaptureProtocolMethod,
71
+ searchableText,
72
+ } from "./persistence/backend.ts";
73
+ export {
74
+ AgentDatabaseInUseError,
75
+ SQLITE_AGENT_SCHEMA_VERSION,
76
+ SqliteAgentPersistence,
77
+ hasSafeConcurrentWal,
78
+ requireSqliteSearch,
79
+ } from "./persistence/index.ts";
80
+ export type { SqliteAgentPersistenceConfig } from "./persistence/index.ts";
81
+ export type {
82
+ AgentConversationSummary,
83
+ AgentAuditState,
84
+ AuditOutboxBacklog,
85
+ AgentPersistenceIdentity,
86
+ ConversationRecord,
87
+ ConversationRecordCaptureConfig,
88
+ ConversationRecordCapturePolicy,
89
+ ConversationRecordEnvelope,
90
+ ConversationRecordKind,
91
+ IdentityMemoryObservation,
92
+ MessageRecord,
93
+ AgentMeteringCommitInput,
94
+ MeteringCommitInput,
95
+ MeteringPersistence,
96
+ MeteringRecordListOptions,
97
+ MeteringRecordPage,
98
+ MeteringRecordRetention,
99
+ MeteringReferenceRecord,
100
+ ProtocolRecordCapture,
101
+ ProtocolRecordCaptureLevel,
102
+ ProtocolRecordCaptureOptions,
103
+ RecordCaptureLevel,
104
+ ResolvedProtocolRecordCapturePolicy,
105
+ NewConversationRecord,
106
+ NewAuditOutboxItem,
107
+ ParticipantKind,
108
+ ParticipantRef,
109
+ PersistedContent,
110
+ PersistedContentBlock,
111
+ PersistedIdentitySnapshot,
112
+ PersistedAgentMeteringState,
113
+ PersistedConversationMeteringState,
114
+ PersistenceBackend,
115
+ PersistenceCapabilities,
116
+ PersistenceExtension,
117
+ PersistenceJsonValue,
118
+ PersistenceScope,
119
+ SearchMatch,
120
+ SearchQuery,
121
+ VectorIndex,
122
+ } from "./persistence/backend.ts";
123
+
20
124
  export {
21
125
  AgentController,
22
126
  parseConfigValue,
@@ -35,6 +139,7 @@ export type {
35
139
  } from "./controller.ts";
36
140
 
37
141
  export {
142
+ AgentConversation,
38
143
  AgentSession,
39
144
  AgentSessionPromptBlockedError,
40
145
  AdapterMismatchError,
@@ -42,6 +147,18 @@ export {
42
147
  DirectAuditPersistenceUnsupportedError,
43
148
  } from "./agent-session.ts";
44
149
  export type {
150
+ AgentConversationConfig,
151
+ AgentConversationOpenConfig,
152
+ AgentConversationOpenResult,
153
+ AgentConversationPromptability,
154
+ AgentConversationPhase,
155
+ AgentConversationState,
156
+ AgentConversationEvent,
157
+ AgentConversationNotification,
158
+ AgentConversationListener,
159
+ AgentConversationPromptResult,
160
+ AgentConversationRecoveryResolution,
161
+ AgentConversationRecoveryResolutionResult,
45
162
  AgentSessionConfig,
46
163
  AgentSessionOpenConfig,
47
164
  AgentSessionOpenResult,
@@ -135,6 +252,10 @@ export {
135
252
  ManagedAgentSessionNotFoundError,
136
253
  } from "./persistence/managed-load.ts";
137
254
  export type { ManagedAgentSessionLoadConfig } from "./persistence/managed-load.ts";
255
+ export type {
256
+ AgentSessionOpenStage,
257
+ AgentSessionOpenProgressListener,
258
+ } from "./persistence/managed-open-progress.ts";
138
259
  export type {
139
260
  GetAgentSessionCheckpointOptions,
140
261
  ResolvedAgentSessionCheckpoint,
@@ -0,0 +1,68 @@
1
+ import type { InternalInferenceRuntime } from "./contracts.ts";
2
+
3
+ export type InternalInferenceRetention = "all" | { readonly retain: number };
4
+
5
+ export interface InternalInferenceRetryPolicy {
6
+ readonly maxAttempts: number;
7
+ readonly backoffMs: readonly number[];
8
+ }
9
+
10
+ export interface InternalInferenceConfig {
11
+ readonly runtime?: InternalInferenceRuntime;
12
+ readonly adapter?: "same" | string;
13
+ readonly maxConcurrency?: number;
14
+ readonly leaseDurationMs?: number;
15
+ readonly heartbeatIntervalMs?: number;
16
+ readonly shutdownGraceMs?: number;
17
+ readonly retry?: Partial<InternalInferenceRetryPolicy>;
18
+ readonly retention?: InternalInferenceRetention;
19
+ }
20
+
21
+ export interface ResolvedInternalInferenceConfig {
22
+ readonly runtime?: InternalInferenceRuntime;
23
+ readonly adapter: "same" | string;
24
+ readonly maxConcurrency: number;
25
+ readonly leaseDurationMs: number;
26
+ readonly heartbeatIntervalMs: number;
27
+ readonly shutdownGraceMs: number;
28
+ readonly retry: InternalInferenceRetryPolicy;
29
+ readonly retention: InternalInferenceRetention;
30
+ }
31
+
32
+ export function resolveInternalInferenceConfig(
33
+ config: InternalInferenceConfig = {},
34
+ ): ResolvedInternalInferenceConfig {
35
+ const leaseDurationMs = integer(config.leaseDurationMs ?? 30_000, 1_000, "leaseDurationMs");
36
+ const heartbeatIntervalMs = integer(
37
+ config.heartbeatIntervalMs ?? 10_000,
38
+ 250,
39
+ "heartbeatIntervalMs",
40
+ );
41
+ if (heartbeatIntervalMs >= leaseDurationMs) {
42
+ throw new Error("internal inference heartbeatIntervalMs must be shorter than leaseDurationMs");
43
+ }
44
+ const maxAttempts = integer(config.retry?.maxAttempts ?? 3, 1, "retry.maxAttempts");
45
+ const backoffMs = config.retry?.backoffMs ?? [1_000, 10_000, 60_000];
46
+ if (backoffMs.some((value) => !Number.isSafeInteger(value) || value < 0)) {
47
+ throw new Error("internal inference retry.backoffMs must contain non-negative integers");
48
+ }
49
+ const retention = config.retention ?? "all";
50
+ if (retention !== "all") integer(retention.retain, 0, "retention.retain");
51
+ return Object.freeze({
52
+ ...(config.runtime ? { runtime: config.runtime } : {}),
53
+ adapter: config.adapter ?? "same",
54
+ maxConcurrency: integer(config.maxConcurrency ?? 1, 1, "maxConcurrency"),
55
+ leaseDurationMs,
56
+ heartbeatIntervalMs,
57
+ shutdownGraceMs: integer(config.shutdownGraceMs ?? 2_000, 0, "shutdownGraceMs"),
58
+ retry: Object.freeze({ maxAttempts, backoffMs: Object.freeze([...backoffMs]) }),
59
+ retention,
60
+ });
61
+ }
62
+
63
+ function integer(value: number, minimum: number, name: string): number {
64
+ if (!Number.isSafeInteger(value) || value < minimum) {
65
+ throw new Error(`internal inference ${name} must be an integer >= ${minimum}`);
66
+ }
67
+ return value;
68
+ }
@@ -0,0 +1,218 @@
1
+ import type { AgentConversationId, AgentSessionId } from "../agent-ids.ts";
2
+ import type { AgentSessionMeteringState } from "../metering/state.ts";
3
+ import type { OperationMeteringRecord, OperationOutcome } from "../metering/record.ts";
4
+ import type { StatefulSubscribable, Subscribable } from "../observation/contracts.ts";
5
+ import type { PersistenceJsonValue, PersistenceScope } from "../persistence/backend.ts";
6
+ import type { ResponseMessage, TokenUsage } from "../types.ts";
7
+
8
+ export type InternalInferenceId = `aii-${string}`;
9
+ export type BuiltinInternalInferencePurpose =
10
+ | "conversation_checkpoint"
11
+ | "conversation_recovery"
12
+ | "identity_update";
13
+ export type InternalInferencePurpose = BuiltinInternalInferencePurpose | (string & {});
14
+ export type InternalInferenceStatus = "queued" | "running" | "completed" | "failed" | "cancelled";
15
+ export type InternalInferenceChainStatus = "active" | "completed" | "failed" | "cancelled";
16
+ export type InternalInferenceStage =
17
+ | "queued"
18
+ | "claiming"
19
+ | "preparing_input"
20
+ | "starting_harness"
21
+ | "creating_session"
22
+ | "prompting"
23
+ | "persisting_result"
24
+ | "completed"
25
+ | "retry_wait"
26
+ | "failed"
27
+ | "cancelled";
28
+
29
+ export interface InternalInferenceInputDescriptor {
30
+ readonly version: number;
31
+ readonly strategyId: string;
32
+ readonly payload: PersistenceJsonValue;
33
+ }
34
+
35
+ export interface InternalInferenceRequest {
36
+ readonly internalInferenceId: InternalInferenceId;
37
+ readonly purpose: InternalInferencePurpose;
38
+ readonly agentSessionId: AgentSessionId;
39
+ readonly agentConversationId?: AgentConversationId;
40
+ readonly adapterId: string;
41
+ readonly prompt: string;
42
+ readonly cwd?: string;
43
+ readonly metadata?: string;
44
+ }
45
+
46
+ export interface InternalInferenceResult {
47
+ readonly internalInferenceId: InternalInferenceId;
48
+ readonly internalSessionId: string;
49
+ readonly adapterId: string;
50
+ readonly model: string | null;
51
+ readonly messages: readonly ResponseMessage[];
52
+ readonly usage: TokenUsage | null;
53
+ readonly stopReason?: string;
54
+ readonly metadata?: string;
55
+ }
56
+
57
+ export interface InternalInferenceCompletion {
58
+ readonly internalInferenceId: InternalInferenceId;
59
+ readonly rootInternalInferenceId: InternalInferenceId;
60
+ readonly internalSessionId: string;
61
+ readonly purpose: InternalInferencePurpose;
62
+ readonly artifactId?: string;
63
+ readonly meteringOperationId?: string;
64
+ readonly completedAt: string;
65
+ readonly metadata?: string;
66
+ }
67
+
68
+ export interface InternalInferenceSnapshot {
69
+ readonly id: InternalInferenceId;
70
+ readonly rootId: InternalInferenceId;
71
+ readonly agentSessionId: AgentSessionId;
72
+ readonly retryOfId?: InternalInferenceId;
73
+ readonly revision: number;
74
+ readonly purpose: InternalInferencePurpose;
75
+ readonly status: InternalInferenceStatus;
76
+ readonly stage: InternalInferenceStage;
77
+ readonly adapterId: string;
78
+ readonly agentConversationId?: AgentConversationId;
79
+ readonly sourceCheckpointId?: string;
80
+ readonly sourceFromSequence?: number;
81
+ readonly sourceThroughSequence?: number;
82
+ readonly requestedAt: string;
83
+ readonly startedAt?: string;
84
+ readonly completedAt?: string;
85
+ readonly attemptNumber: number;
86
+ readonly error?: string;
87
+ }
88
+
89
+ export interface InternalInferenceRunSnapshot {
90
+ readonly rootId: InternalInferenceId;
91
+ readonly status: InternalInferenceChainStatus;
92
+ readonly revision: number;
93
+ readonly activeAttemptId?: InternalInferenceId;
94
+ readonly requestedThroughSequence?: number;
95
+ readonly error?: string;
96
+ }
97
+
98
+ export interface InternalInferenceEvent {
99
+ readonly kind: "changed";
100
+ /** Monotonic within one manager process, including ephemeral progress changes. */
101
+ readonly sequence: number;
102
+ readonly inferenceId: InternalInferenceId;
103
+ readonly rootId: InternalInferenceId;
104
+ readonly revision: number;
105
+ readonly snapshot: InternalInferenceSnapshot;
106
+ }
107
+
108
+ export interface InternalInference extends StatefulSubscribable<InternalInferenceSnapshot, InternalInferenceEvent> {
109
+ readonly id: InternalInferenceId;
110
+ readonly result: Promise<InternalInferenceCompletion>;
111
+ cancel(): Promise<void>;
112
+ }
113
+
114
+ export interface InternalInferenceRun extends StatefulSubscribable<InternalInferenceRunSnapshot, InternalInferenceEvent> {
115
+ readonly rootId: InternalInferenceId;
116
+ readonly activeAttempt: InternalInference;
117
+ readonly result: Promise<InternalInferenceCompletion>;
118
+ cancel(): Promise<void>;
119
+ }
120
+
121
+ export interface EnqueueInternalInferenceRequest {
122
+ readonly purpose: InternalInferencePurpose;
123
+ readonly agentConversationId?: AgentConversationId;
124
+ /** Overrides the configured policy; otherwise the manager resolves and snapshots it. */
125
+ readonly adapterId?: string;
126
+ readonly executionProfileId?: string;
127
+ readonly input: InternalInferenceInputDescriptor;
128
+ readonly sourceCheckpointId?: string;
129
+ readonly sourceFromSequence?: number;
130
+ readonly sourceThroughSequence?: number;
131
+ readonly requestedThroughSequence?: number;
132
+ readonly metadata?: string;
133
+ }
134
+
135
+ export interface InternalInferenceManager extends Subscribable<InternalInferenceEvent> {
136
+ enqueue(request: EnqueueInternalInferenceRequest): Promise<InternalInferenceRun>;
137
+ getAttempt(id: InternalInferenceId): Promise<InternalInference | null>;
138
+ getRun(rootId: InternalInferenceId): Promise<InternalInferenceRun | null>;
139
+ list(options?: InternalInferenceListOptions): Promise<InternalInferenceSnapshotPage>;
140
+ cancel(rootId: InternalInferenceId, reason?: string): Promise<void>;
141
+ }
142
+
143
+ export interface InternalInferenceListOptions {
144
+ readonly agentConversationId?: AgentConversationId;
145
+ readonly purpose?: InternalInferencePurpose;
146
+ readonly status?: InternalInferenceStatus;
147
+ readonly rootId?: InternalInferenceId;
148
+ readonly limit?: number;
149
+ readonly cursor?: string;
150
+ }
151
+
152
+ export interface InternalInferenceSnapshotPage {
153
+ readonly attempts: readonly InternalInferenceSnapshot[];
154
+ readonly nextCursor?: string;
155
+ }
156
+
157
+ export interface InternalInferenceRuntime {
158
+ run(
159
+ request: InternalInferenceRequest,
160
+ signal?: AbortSignal,
161
+ lifecycle?: InternalInferenceRuntimeLifecycle,
162
+ ): Promise<InternalInferenceResult>;
163
+ }
164
+
165
+ export interface InternalInferenceRuntimeLifecycle {
166
+ stageChanged?(stage: Extract<InternalInferenceStage, "creating_session" | "prompting">): void;
167
+ sessionStarted(input: {
168
+ readonly internalSessionId: string;
169
+ readonly model: string | null;
170
+ }): void | Promise<void>;
171
+ }
172
+
173
+ export interface InternalInferenceMeteringOperation {
174
+ close(input: {
175
+ readonly outcome: OperationOutcome;
176
+ readonly result?: InternalInferenceResult;
177
+ readonly error?: unknown;
178
+ }): Promise<OperationMeteringRecord>;
179
+ /** Releases restoration barriers after the record transaction settles. */
180
+ settled(): void;
181
+ }
182
+
183
+ export type InternalInferenceRetryDisposition =
184
+ | { readonly kind: "terminal"; readonly code: string }
185
+ | { readonly kind: "retryable"; readonly code: string };
186
+
187
+ export interface PreparedInternalInference {
188
+ readonly prompt: string;
189
+ readonly cwd?: string;
190
+ readonly metadata?: string;
191
+ }
192
+
193
+ export interface InternalInferencePreparationContext {
194
+ readonly attempt: InternalInferenceSnapshot;
195
+ /** Canonical agent persistence used to derive the prompt from durable source data. */
196
+ readonly persistence: PersistenceScope;
197
+ readonly signal?: AbortSignal;
198
+ }
199
+
200
+ export interface InternalInferenceCompletionContext {
201
+ readonly attempt: InternalInferenceSnapshot;
202
+ /** Transaction-scoped persistence used to publish the purpose artifact atomically. */
203
+ readonly persistence: PersistenceScope;
204
+ readonly meteringState?: AgentSessionMeteringState;
205
+ }
206
+
207
+ export interface InternalInferenceStrategy<TPayload = PersistenceJsonValue> {
208
+ readonly strategyId: string;
209
+ readonly purpose: InternalInferencePurpose;
210
+ readonly version: number;
211
+ validatePayload(payload: PersistenceJsonValue): TPayload;
212
+ prepare(context: InternalInferencePreparationContext, payload: TPayload): Promise<PreparedInternalInference>;
213
+ complete(
214
+ context: InternalInferenceCompletionContext,
215
+ result: InternalInferenceResult,
216
+ ): Promise<InternalInferenceCompletion>;
217
+ classifyError(error: unknown): InternalInferenceRetryDisposition;
218
+ }