@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.
- package/CHANGELOG-audit.md +58 -0
- package/CONSUMER_GUIDE.md +452 -19
- package/package.json +6 -1
- package/src/agent-adapter-registry.ts +66 -0
- package/src/agent-conversation-continuation.ts +121 -0
- package/src/agent-conversation-contracts.ts +279 -0
- package/src/agent-conversation-errors.ts +31 -0
- package/src/agent-conversation-owner.ts +55 -0
- package/src/agent-conversation-presentation.ts +217 -0
- package/src/agent-conversation-queue.ts +44 -0
- package/src/agent-conversation.ts +41 -0
- package/src/agent-ids.ts +50 -0
- package/src/agent-session.ts +973 -673
- package/src/agent.ts +1175 -0
- package/src/audit/config.ts +186 -0
- package/src/audit/contracts.ts +59 -0
- package/src/audit/index.ts +50 -0
- package/src/audit/projection.ts +125 -0
- package/src/audit/reader.ts +371 -0
- package/src/audit/runtime.ts +1060 -0
- package/src/checkpointing/config.ts +91 -0
- package/src/checkpointing/contracts.ts +45 -0
- package/src/checkpointing/coordinator.ts +100 -0
- package/src/checkpointing/ids.ts +5 -0
- package/src/checkpointing/index.ts +6 -0
- package/src/checkpointing/persistence/sqlite-repository.ts +159 -0
- package/src/checkpointing/recovery.ts +114 -0
- package/src/checkpointing/strategy.ts +139 -0
- package/src/identity.ts +62 -0
- package/src/index.ts +117 -0
- package/src/internal-inference/config.ts +68 -0
- package/src/internal-inference/contracts.ts +218 -0
- package/src/internal-inference/coordination/handles.ts +133 -0
- package/src/internal-inference/coordination/manager.ts +487 -0
- package/src/internal-inference/ids.ts +10 -0
- package/src/internal-inference/index.ts +10 -0
- package/src/internal-inference/persistence/records.ts +132 -0
- package/src/internal-inference/persistence/repository.ts +35 -0
- package/src/internal-inference/persistence/sqlite-repository.ts +551 -0
- package/src/internal-inference/runtime/harness-runtime.ts +78 -0
- package/src/internal-inference/strategy/registry.ts +42 -0
- package/src/metering/engine.ts +47 -0
- package/src/metering/record.ts +4 -1
- package/src/observation/contracts.ts +10 -0
- package/src/observation/index.ts +8 -0
- package/src/observation/subscription-hub.ts +43 -0
- package/src/persistence/activity-projection.ts +26 -12
- package/src/persistence/backend.ts +774 -0
- package/src/persistence/index.ts +99 -0
- package/src/persistence/sqlite-backend.ts +1927 -0
- package/src/persistence/sqlite-conversation-records.ts +425 -0
- package/src/persistence/sqlite-owner-lock.ts +106 -0
- package/src/persistence/sqlite-schema.ts +561 -0
package/src/identity.ts
ADDED
|
@@ -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,
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { SubscriptionHub } from "../../observation/subscription-hub.ts";
|
|
2
|
+
import type {
|
|
3
|
+
InternalInference,
|
|
4
|
+
InternalInferenceCompletion,
|
|
5
|
+
InternalInferenceEvent,
|
|
6
|
+
InternalInferenceId,
|
|
7
|
+
InternalInferenceRun,
|
|
8
|
+
InternalInferenceRunSnapshot,
|
|
9
|
+
InternalInferenceSnapshot,
|
|
10
|
+
} from "../contracts.ts";
|
|
11
|
+
import type {
|
|
12
|
+
InternalInferenceAttemptRecord,
|
|
13
|
+
InternalInferenceChainRecord,
|
|
14
|
+
} from "../persistence/records.ts";
|
|
15
|
+
|
|
16
|
+
export class AttemptHandle implements InternalInference {
|
|
17
|
+
private readonly hub = new SubscriptionHub<InternalInferenceEvent>();
|
|
18
|
+
private current: InternalInferenceSnapshot;
|
|
19
|
+
private readonly deferred = promiseWithResolvers<InternalInferenceCompletion>();
|
|
20
|
+
readonly result = this.deferred.promise;
|
|
21
|
+
|
|
22
|
+
constructor(record: InternalInferenceAttemptRecord, private readonly cancelRun: (reason?: string) => Promise<void>) {
|
|
23
|
+
this.current = snapshotOf(record);
|
|
24
|
+
this.result.catch(() => {});
|
|
25
|
+
this.settle(record);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
get id(): InternalInferenceId { return this.current.id; }
|
|
29
|
+
get snapshot(): InternalInferenceSnapshot { return this.current; }
|
|
30
|
+
subscribe(listener: (event: InternalInferenceEvent) => void): () => void { return this.hub.subscribe(listener); }
|
|
31
|
+
cancel(): Promise<void> { return this.cancelRun(); }
|
|
32
|
+
emit(event: InternalInferenceEvent): void { this.hub.emit(event); }
|
|
33
|
+
update(record: InternalInferenceAttemptRecord): void {
|
|
34
|
+
if (record.revision < this.current.revision) return;
|
|
35
|
+
this.current = snapshotOf(record);
|
|
36
|
+
this.settle(record);
|
|
37
|
+
}
|
|
38
|
+
setStage(stage: InternalInferenceSnapshot["stage"]): void {
|
|
39
|
+
if (this.current.status !== "running") return;
|
|
40
|
+
this.current = Object.freeze({ ...this.current, stage });
|
|
41
|
+
}
|
|
42
|
+
private settle(record: InternalInferenceAttemptRecord): void {
|
|
43
|
+
if (record.status === "completed" && record.completion) this.deferred.resolve(record.completion);
|
|
44
|
+
if (record.status === "failed" || record.status === "cancelled") {
|
|
45
|
+
this.deferred.reject(new Error(record.error ?? `internal inference ${record.status}`));
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export class RunHandle implements InternalInferenceRun {
|
|
51
|
+
private readonly hub = new SubscriptionHub<InternalInferenceEvent>();
|
|
52
|
+
private current: InternalInferenceRunSnapshot;
|
|
53
|
+
private attempt: InternalInference;
|
|
54
|
+
private readonly deferred = promiseWithResolvers<InternalInferenceCompletion>();
|
|
55
|
+
readonly result = this.deferred.promise;
|
|
56
|
+
|
|
57
|
+
constructor(
|
|
58
|
+
chain: InternalInferenceChainRecord,
|
|
59
|
+
attempt: InternalInference,
|
|
60
|
+
private readonly cancelRun: (reason?: string) => Promise<void>,
|
|
61
|
+
) {
|
|
62
|
+
this.current = runSnapshotOf(chain);
|
|
63
|
+
this.attempt = attempt;
|
|
64
|
+
this.result.catch(() => {});
|
|
65
|
+
this.settle(chain, attempt);
|
|
66
|
+
}
|
|
67
|
+
get rootId(): InternalInferenceId { return this.current.rootId; }
|
|
68
|
+
get activeAttempt(): InternalInference { return this.attempt; }
|
|
69
|
+
get snapshot(): InternalInferenceRunSnapshot { return this.current; }
|
|
70
|
+
subscribe(listener: (event: InternalInferenceEvent) => void): () => void { return this.hub.subscribe(listener); }
|
|
71
|
+
cancel(): Promise<void> { return this.cancelRun(); }
|
|
72
|
+
update(chain: InternalInferenceChainRecord, attempt: InternalInference): void {
|
|
73
|
+
if (chain.revision < this.current.revision) return;
|
|
74
|
+
this.current = runSnapshotOf(chain);
|
|
75
|
+
this.attempt = attempt;
|
|
76
|
+
this.settle(chain, attempt);
|
|
77
|
+
}
|
|
78
|
+
private settle(chain: InternalInferenceChainRecord, attempt: InternalInference): void {
|
|
79
|
+
if (chain.status === "completed") void attempt.result.then(this.deferred.resolve, this.deferred.reject);
|
|
80
|
+
if (chain.status === "failed" || chain.status === "cancelled") {
|
|
81
|
+
this.deferred.reject(new Error(chain.error ?? `internal inference run ${chain.status}`));
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function snapshotOf(record: InternalInferenceAttemptRecord): InternalInferenceSnapshot {
|
|
87
|
+
return Object.freeze({
|
|
88
|
+
id: record.internalInferenceId,
|
|
89
|
+
rootId: record.rootInternalInferenceId,
|
|
90
|
+
agentSessionId: record.agentSessionId,
|
|
91
|
+
...(record.retryOfInternalInferenceId ? { retryOfId: record.retryOfInternalInferenceId } : {}),
|
|
92
|
+
revision: record.revision,
|
|
93
|
+
purpose: record.purpose,
|
|
94
|
+
status: record.status,
|
|
95
|
+
stage: record.status === "running" ? "prompting" : record.status,
|
|
96
|
+
adapterId: record.adapterId,
|
|
97
|
+
...(record.agentConversationId ? { agentConversationId: record.agentConversationId } : {}),
|
|
98
|
+
...(record.sourceCheckpointId ? { sourceCheckpointId: record.sourceCheckpointId } : {}),
|
|
99
|
+
...(record.sourceFromSequence === undefined
|
|
100
|
+
? {}
|
|
101
|
+
: { sourceFromSequence: record.sourceFromSequence }),
|
|
102
|
+
...(record.sourceThroughSequence === undefined
|
|
103
|
+
? {}
|
|
104
|
+
: { sourceThroughSequence: record.sourceThroughSequence }),
|
|
105
|
+
requestedAt: record.requestedAt,
|
|
106
|
+
...(record.startedAt ? { startedAt: record.startedAt } : {}),
|
|
107
|
+
...(record.completedAt ? { completedAt: record.completedAt } : {}),
|
|
108
|
+
attemptNumber: record.attemptNumber,
|
|
109
|
+
...(record.error ? { error: record.error } : {}),
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function runSnapshotOf(chain: InternalInferenceChainRecord): InternalInferenceRunSnapshot {
|
|
114
|
+
return Object.freeze({
|
|
115
|
+
rootId: chain.rootInternalInferenceId,
|
|
116
|
+
status: chain.status,
|
|
117
|
+
revision: chain.revision,
|
|
118
|
+
...(chain.activeInternalInferenceId ? { activeAttemptId: chain.activeInternalInferenceId } : {}),
|
|
119
|
+
...(chain.requestedThroughSequence === undefined ? {} : { requestedThroughSequence: chain.requestedThroughSequence }),
|
|
120
|
+
...(chain.error ? { error: chain.error } : {}),
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function promiseWithResolvers<T>(): {
|
|
125
|
+
promise: Promise<T>;
|
|
126
|
+
resolve: (value: T | PromiseLike<T>) => void;
|
|
127
|
+
reject: (reason?: unknown) => void;
|
|
128
|
+
} {
|
|
129
|
+
let resolve!: (value: T | PromiseLike<T>) => void;
|
|
130
|
+
let reject!: (reason?: unknown) => void;
|
|
131
|
+
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
|
|
132
|
+
return { promise, resolve, reject };
|
|
133
|
+
}
|