@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
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import type { AgentSessionId } from "../../agent-ids.ts";
|
|
3
|
+
import type { PersistenceBackend } from "../../persistence/backend.ts";
|
|
4
|
+
import type { OperationMeteringRecord } from "../../metering/record.ts";
|
|
5
|
+
import { SubscriptionHub } from "../../observation/subscription-hub.ts";
|
|
6
|
+
import { createInternalInferenceId } from "../ids.ts";
|
|
7
|
+
import type {
|
|
8
|
+
EnqueueInternalInferenceRequest,
|
|
9
|
+
InternalInference,
|
|
10
|
+
InternalInferenceEvent,
|
|
11
|
+
InternalInferenceId,
|
|
12
|
+
InternalInferenceManager,
|
|
13
|
+
InternalInferenceMeteringOperation,
|
|
14
|
+
InternalInferenceListOptions,
|
|
15
|
+
InternalInferenceRun,
|
|
16
|
+
InternalInferenceSnapshot,
|
|
17
|
+
InternalInferenceSnapshotPage,
|
|
18
|
+
InternalInferenceStrategy,
|
|
19
|
+
} from "../contracts.ts";
|
|
20
|
+
import type { ResolvedInternalInferenceConfig } from "../config.ts";
|
|
21
|
+
import type { InternalInferenceRepository } from "../persistence/repository.ts";
|
|
22
|
+
import type {
|
|
23
|
+
InternalInferenceAttemptRecord,
|
|
24
|
+
InternalInferenceChainRecord,
|
|
25
|
+
} from "../persistence/records.ts";
|
|
26
|
+
import { InternalInferenceStrategyRegistry } from "../strategy/registry.ts";
|
|
27
|
+
import { AttemptHandle, RunHandle, snapshotOf } from "./handles.ts";
|
|
28
|
+
|
|
29
|
+
export interface DefaultInternalInferenceManagerConfig {
|
|
30
|
+
readonly agentSessionId: AgentSessionId;
|
|
31
|
+
readonly repository: InternalInferenceRepository;
|
|
32
|
+
readonly persistence: PersistenceBackend;
|
|
33
|
+
readonly runtime: NonNullable<ResolvedInternalInferenceConfig["runtime"]>;
|
|
34
|
+
readonly settings: ResolvedInternalInferenceConfig;
|
|
35
|
+
readonly strategies: readonly InternalInferenceStrategy[];
|
|
36
|
+
readonly resolveAdapterId: (
|
|
37
|
+
requestedAdapterId: string | undefined,
|
|
38
|
+
agentConversationId: EnqueueInternalInferenceRequest["agentConversationId"],
|
|
39
|
+
) => string | Promise<string>;
|
|
40
|
+
readonly beginMetering?: (
|
|
41
|
+
attempt: InternalInferenceSnapshot,
|
|
42
|
+
session: { readonly internalSessionId: string; readonly model: string | null },
|
|
43
|
+
) => Promise<InternalInferenceMeteringOperation | null>;
|
|
44
|
+
readonly meteringRecords?: import("../../persistence/backend.ts").MeteringRecordRetention;
|
|
45
|
+
readonly pollIntervalMs?: number;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Agent-scoped durable scheduler. Purpose-specific artifact transactions remain strategies' responsibility. */
|
|
49
|
+
export class DefaultInternalInferenceManager implements InternalInferenceManager {
|
|
50
|
+
private readonly hub = new SubscriptionHub<InternalInferenceEvent>();
|
|
51
|
+
private readonly registry: InternalInferenceStrategyRegistry;
|
|
52
|
+
private readonly workerId = `iiw-${randomUUID()}`;
|
|
53
|
+
private readonly attempts = new Map<InternalInferenceId, AttemptHandle>();
|
|
54
|
+
private readonly runs = new Map<InternalInferenceId, RunHandle>();
|
|
55
|
+
private readonly active = new Map<InternalInferenceId, {
|
|
56
|
+
abort: AbortController;
|
|
57
|
+
leaseToken: string;
|
|
58
|
+
attempt: InternalInferenceAttemptRecord;
|
|
59
|
+
metering: InternalInferenceMeteringOperation | null;
|
|
60
|
+
}>();
|
|
61
|
+
private readonly fenced = new Set<InternalInferenceId>();
|
|
62
|
+
private readonly pollIntervalMs: number;
|
|
63
|
+
private timer?: ReturnType<typeof setTimeout>;
|
|
64
|
+
private pumping = false;
|
|
65
|
+
private closed = false;
|
|
66
|
+
private eventSequence = 0;
|
|
67
|
+
|
|
68
|
+
constructor(private readonly config: DefaultInternalInferenceManagerConfig) {
|
|
69
|
+
this.registry = new InternalInferenceStrategyRegistry(config.strategies);
|
|
70
|
+
this.pollIntervalMs = config.pollIntervalMs ?? 250;
|
|
71
|
+
this.wake();
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
subscribe(listener: (event: InternalInferenceEvent) => void): () => void {
|
|
75
|
+
return this.hub.subscribe(listener);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async enqueue(request: EnqueueInternalInferenceRequest): Promise<InternalInferenceRun> {
|
|
79
|
+
this.assertOpen();
|
|
80
|
+
const strategy = this.registry.require(request.purpose, request.input.strategyId, request.input.version);
|
|
81
|
+
strategy.validatePayload(request.input.payload);
|
|
82
|
+
const adapterId = await this.config.resolveAdapterId(
|
|
83
|
+
request.adapterId,
|
|
84
|
+
request.agentConversationId,
|
|
85
|
+
);
|
|
86
|
+
const id = createInternalInferenceId();
|
|
87
|
+
const persisted = await this.config.repository.enqueue({
|
|
88
|
+
internalInferenceId: id,
|
|
89
|
+
agentSessionId: this.config.agentSessionId,
|
|
90
|
+
...(request.agentConversationId ? { agentConversationId: request.agentConversationId } : {}),
|
|
91
|
+
purpose: request.purpose,
|
|
92
|
+
adapterId,
|
|
93
|
+
...(request.executionProfileId ? { executionProfileId: request.executionProfileId } : {}),
|
|
94
|
+
input: request.input,
|
|
95
|
+
...(request.sourceCheckpointId ? { sourceCheckpointId: request.sourceCheckpointId } : {}),
|
|
96
|
+
...(request.sourceFromSequence === undefined ? {} : { sourceFromSequence: request.sourceFromSequence }),
|
|
97
|
+
...(request.sourceThroughSequence === undefined ? {} : { sourceThroughSequence: request.sourceThroughSequence }),
|
|
98
|
+
...(request.requestedThroughSequence === undefined
|
|
99
|
+
? {}
|
|
100
|
+
: { requestedThroughSequence: request.requestedThroughSequence }),
|
|
101
|
+
...(request.metadata ? { metadata: request.metadata } : {}),
|
|
102
|
+
});
|
|
103
|
+
const run = this.ownRun(persisted.chain, persisted.attempt);
|
|
104
|
+
this.wake();
|
|
105
|
+
return run;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async getAttempt(id: InternalInferenceId): Promise<InternalInference | null> {
|
|
109
|
+
const record = await this.config.repository.getAttempt(id);
|
|
110
|
+
return record ? this.ownAttempt(record) : null;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async getRun(rootId: InternalInferenceId): Promise<InternalInferenceRun | null> {
|
|
114
|
+
const chain = await this.config.repository.getChain(rootId);
|
|
115
|
+
if (!chain) return null;
|
|
116
|
+
const activeId = chain.activeInternalInferenceId ?? rootId;
|
|
117
|
+
const attempt = await this.config.repository.getAttempt(activeId);
|
|
118
|
+
if (!attempt) return null;
|
|
119
|
+
return this.ownRun(chain, attempt);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async list(options: InternalInferenceListOptions = {}): Promise<InternalInferenceSnapshotPage> {
|
|
123
|
+
const page = await this.config.repository.list(options);
|
|
124
|
+
return Object.freeze({
|
|
125
|
+
attempts: Object.freeze(page.attempts.map((record) => snapshotOf(record))),
|
|
126
|
+
...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async cancel(rootId: InternalInferenceId, reason?: string): Promise<void> {
|
|
131
|
+
const current = await this.config.repository.getChain(rootId);
|
|
132
|
+
if (current?.activeInternalInferenceId) {
|
|
133
|
+
this.active.get(current.activeInternalInferenceId)?.abort.abort();
|
|
134
|
+
}
|
|
135
|
+
const chain = await this.config.repository.cancel(rootId, reason);
|
|
136
|
+
await this.refreshChain(chain);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async close(): Promise<void> {
|
|
140
|
+
if (this.closed) return;
|
|
141
|
+
this.closed = true;
|
|
142
|
+
if (this.timer) clearTimeout(this.timer);
|
|
143
|
+
for (const execution of this.active.values()) execution.abort.abort();
|
|
144
|
+
const deadline = Date.now() + this.config.settings.shutdownGraceMs;
|
|
145
|
+
while (this.active.size && Date.now() < deadline) {
|
|
146
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(25, Math.max(1, deadline - Date.now()))));
|
|
147
|
+
}
|
|
148
|
+
for (const [id, execution] of this.active) {
|
|
149
|
+
this.fenced.add(id);
|
|
150
|
+
execution.metering?.settled();
|
|
151
|
+
const canRetry = execution.attempt.attemptNumber < this.config.settings.retry.maxAttempts;
|
|
152
|
+
await this.config.repository.fail({
|
|
153
|
+
internalInferenceId: id,
|
|
154
|
+
workerId: this.workerId,
|
|
155
|
+
leaseToken: execution.leaseToken,
|
|
156
|
+
error: "agent shutdown interrupted internal inference",
|
|
157
|
+
failureCode: "shutdown_interrupted",
|
|
158
|
+
...(canRetry ? { retry: { internalInferenceId: createInternalInferenceId() } } : {}),
|
|
159
|
+
}).catch(() => undefined);
|
|
160
|
+
}
|
|
161
|
+
this.hub.clear();
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
private wake(): void {
|
|
165
|
+
if (this.closed || this.timer) return;
|
|
166
|
+
this.timer = setTimeout(() => {
|
|
167
|
+
this.timer = undefined;
|
|
168
|
+
void this.pump();
|
|
169
|
+
}, 0);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
private async pump(): Promise<void> {
|
|
173
|
+
if (this.closed || this.pumping) return;
|
|
174
|
+
this.pumping = true;
|
|
175
|
+
try {
|
|
176
|
+
while (!this.closed) {
|
|
177
|
+
const recovered = await this.config.repository.recoverExpired({
|
|
178
|
+
retryInternalInferenceId: createInternalInferenceId(),
|
|
179
|
+
maxAttempts: this.config.settings.retry.maxAttempts,
|
|
180
|
+
});
|
|
181
|
+
if (!recovered) break;
|
|
182
|
+
this.publishAttempt(recovered);
|
|
183
|
+
await this.refreshRun(recovered.rootInternalInferenceId);
|
|
184
|
+
}
|
|
185
|
+
while (!this.closed && this.active.size < this.config.settings.maxConcurrency) {
|
|
186
|
+
const leaseToken = randomUUID();
|
|
187
|
+
const claimed = await this.config.repository.claimNext({
|
|
188
|
+
workerId: this.workerId,
|
|
189
|
+
leaseToken,
|
|
190
|
+
leaseDurationMs: this.config.settings.leaseDurationMs,
|
|
191
|
+
});
|
|
192
|
+
if (!claimed) break;
|
|
193
|
+
const abort = new AbortController();
|
|
194
|
+
this.active.set(claimed.attempt.internalInferenceId, {
|
|
195
|
+
abort,
|
|
196
|
+
leaseToken,
|
|
197
|
+
attempt: claimed.attempt,
|
|
198
|
+
metering: null,
|
|
199
|
+
});
|
|
200
|
+
this.publishAttempt(claimed.attempt);
|
|
201
|
+
void this.execute(claimed.attempt, abort, leaseToken).catch(() => {});
|
|
202
|
+
}
|
|
203
|
+
} finally {
|
|
204
|
+
this.pumping = false;
|
|
205
|
+
if (!this.closed) {
|
|
206
|
+
this.timer = setTimeout(() => {
|
|
207
|
+
this.timer = undefined;
|
|
208
|
+
void this.pump();
|
|
209
|
+
}, this.pollIntervalMs);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
private async execute(
|
|
215
|
+
attempt: InternalInferenceAttemptRecord,
|
|
216
|
+
abort: AbortController,
|
|
217
|
+
leaseToken: string,
|
|
218
|
+
): Promise<void> {
|
|
219
|
+
let metering: InternalInferenceMeteringOperation | null = null;
|
|
220
|
+
let meteringRecord: OperationMeteringRecord | null = null;
|
|
221
|
+
const heartbeat = setInterval(() => {
|
|
222
|
+
void this.config.repository.heartbeat(
|
|
223
|
+
attempt.internalInferenceId,
|
|
224
|
+
this.workerId,
|
|
225
|
+
leaseToken,
|
|
226
|
+
this.config.settings.leaseDurationMs,
|
|
227
|
+
);
|
|
228
|
+
}, this.config.settings.heartbeatIntervalMs);
|
|
229
|
+
try {
|
|
230
|
+
const strategy = this.registry.require(
|
|
231
|
+
attempt.purpose,
|
|
232
|
+
attempt.input.strategyId,
|
|
233
|
+
attempt.input.version,
|
|
234
|
+
);
|
|
235
|
+
this.publishProgress(attempt.internalInferenceId, "preparing_input");
|
|
236
|
+
const payload = strategy.validatePayload(attempt.input.payload);
|
|
237
|
+
const prepared = await strategy.prepare({
|
|
238
|
+
attempt: snapshotOf(attempt),
|
|
239
|
+
persistence: this.config.persistence,
|
|
240
|
+
signal: abort.signal,
|
|
241
|
+
}, payload);
|
|
242
|
+
this.publishProgress(attempt.internalInferenceId, "starting_harness");
|
|
243
|
+
const result = await this.config.runtime.run({
|
|
244
|
+
internalInferenceId: attempt.internalInferenceId,
|
|
245
|
+
purpose: attempt.purpose,
|
|
246
|
+
agentSessionId: attempt.agentSessionId,
|
|
247
|
+
...(attempt.agentConversationId ? { agentConversationId: attempt.agentConversationId } : {}),
|
|
248
|
+
adapterId: attempt.adapterId,
|
|
249
|
+
prompt: prepared.prompt,
|
|
250
|
+
...(prepared.cwd ? { cwd: prepared.cwd } : {}),
|
|
251
|
+
...(prepared.metadata ? { metadata: prepared.metadata } : {}),
|
|
252
|
+
}, abort.signal, {
|
|
253
|
+
stageChanged: (stage) => this.publishProgress(attempt.internalInferenceId, stage),
|
|
254
|
+
sessionStarted: async (session) => {
|
|
255
|
+
metering = await this.config.beginMetering?.(snapshotOf(attempt), session) ?? null;
|
|
256
|
+
const active = this.active.get(attempt.internalInferenceId);
|
|
257
|
+
if (active) active.metering = metering;
|
|
258
|
+
},
|
|
259
|
+
});
|
|
260
|
+
// Custom runtimes may omit the early lifecycle notification. They lose metering
|
|
261
|
+
// preflight, but their completed provider work must still be accounted for.
|
|
262
|
+
if (!metering && this.config.beginMetering) {
|
|
263
|
+
metering = await this.config.beginMetering(snapshotOf(attempt), {
|
|
264
|
+
internalSessionId: result.internalSessionId,
|
|
265
|
+
model: result.model,
|
|
266
|
+
});
|
|
267
|
+
const active = this.active.get(attempt.internalInferenceId);
|
|
268
|
+
if (active) active.metering = metering;
|
|
269
|
+
}
|
|
270
|
+
if (this.fenced.has(attempt.internalInferenceId)) return;
|
|
271
|
+
this.publishProgress(attempt.internalInferenceId, "persisting_result");
|
|
272
|
+
const openedMetering = metering as InternalInferenceMeteringOperation | null;
|
|
273
|
+
meteringRecord = openedMetering
|
|
274
|
+
? await openedMetering.close({ outcome: "completed", result })
|
|
275
|
+
: null;
|
|
276
|
+
if (this.fenced.has(attempt.internalInferenceId)) return;
|
|
277
|
+
const completed = await this.config.persistence.transaction(async (persistence) => {
|
|
278
|
+
const completion = await strategy.complete({
|
|
279
|
+
attempt: snapshotOf(attempt),
|
|
280
|
+
persistence,
|
|
281
|
+
}, result);
|
|
282
|
+
if (this.fenced.has(attempt.internalInferenceId)) {
|
|
283
|
+
throw new Error("internal inference was fenced during completion");
|
|
284
|
+
}
|
|
285
|
+
if (meteringRecord && attempt.agentConversationId) {
|
|
286
|
+
await persistence.metering.commit({
|
|
287
|
+
agentConversationId: attempt.agentConversationId,
|
|
288
|
+
record: meteringRecord,
|
|
289
|
+
meteringRecords: this.config.meteringRecords ?? "all",
|
|
290
|
+
});
|
|
291
|
+
} else if (meteringRecord) {
|
|
292
|
+
await persistence.metering.commitAgent({
|
|
293
|
+
agentSessionId: attempt.agentSessionId,
|
|
294
|
+
record: meteringRecord,
|
|
295
|
+
meteringRecords: this.config.meteringRecords ?? "all",
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
return await persistence.internalInferences!.complete({
|
|
299
|
+
internalInferenceId: attempt.internalInferenceId,
|
|
300
|
+
workerId: this.workerId,
|
|
301
|
+
leaseToken,
|
|
302
|
+
completion,
|
|
303
|
+
...(result.model ? { model: result.model } : {}),
|
|
304
|
+
internalSessionId: result.internalSessionId,
|
|
305
|
+
...(meteringRecord
|
|
306
|
+
? { meteringOperationId: meteringRecord.operationId }
|
|
307
|
+
: completion.meteringOperationId
|
|
308
|
+
? { meteringOperationId: completion.meteringOperationId }
|
|
309
|
+
: {}),
|
|
310
|
+
});
|
|
311
|
+
});
|
|
312
|
+
this.publishAttempt(completed);
|
|
313
|
+
await this.refreshRun(attempt.rootInternalInferenceId);
|
|
314
|
+
await this.pruneTerminal();
|
|
315
|
+
} catch (error) {
|
|
316
|
+
if (this.fenced.has(attempt.internalInferenceId)) return;
|
|
317
|
+
const openedMetering = metering as InternalInferenceMeteringOperation | null;
|
|
318
|
+
if (openedMetering && !meteringRecord) {
|
|
319
|
+
meteringRecord = await openedMetering.close({ outcome: abort.signal.aborted ? "cancelled" : "error", error })
|
|
320
|
+
.catch(() => null);
|
|
321
|
+
}
|
|
322
|
+
if (this.closed && abort.signal.aborted) {
|
|
323
|
+
await this.recordShutdownInterruption(attempt, leaseToken, error, meteringRecord);
|
|
324
|
+
} else {
|
|
325
|
+
await this.recordFailure(attempt, leaseToken, error, meteringRecord);
|
|
326
|
+
}
|
|
327
|
+
} finally {
|
|
328
|
+
clearInterval(heartbeat);
|
|
329
|
+
(metering as InternalInferenceMeteringOperation | null)?.settled();
|
|
330
|
+
this.active.delete(attempt.internalInferenceId);
|
|
331
|
+
this.wake();
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
private async recordShutdownInterruption(
|
|
336
|
+
attempt: InternalInferenceAttemptRecord,
|
|
337
|
+
leaseToken: string,
|
|
338
|
+
error: unknown,
|
|
339
|
+
meteringRecord: OperationMeteringRecord | null,
|
|
340
|
+
): Promise<void> {
|
|
341
|
+
const canRetry = attempt.attemptNumber < this.config.settings.retry.maxAttempts;
|
|
342
|
+
await this.config.persistence.transaction(async (persistence) => {
|
|
343
|
+
if (meteringRecord && attempt.agentConversationId) {
|
|
344
|
+
await persistence.metering.commit({
|
|
345
|
+
agentConversationId: attempt.agentConversationId,
|
|
346
|
+
record: meteringRecord,
|
|
347
|
+
meteringRecords: this.config.meteringRecords ?? "all",
|
|
348
|
+
});
|
|
349
|
+
} else if (meteringRecord) {
|
|
350
|
+
await persistence.metering.commitAgent({
|
|
351
|
+
agentSessionId: attempt.agentSessionId,
|
|
352
|
+
record: meteringRecord,
|
|
353
|
+
meteringRecords: this.config.meteringRecords ?? "all",
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
await persistence.internalInferences!.fail({
|
|
357
|
+
internalInferenceId: attempt.internalInferenceId,
|
|
358
|
+
workerId: this.workerId,
|
|
359
|
+
leaseToken,
|
|
360
|
+
error: error instanceof Error ? error.message : "agent shutdown interrupted internal inference",
|
|
361
|
+
failureCode: "shutdown_interrupted",
|
|
362
|
+
...(canRetry ? { retry: { internalInferenceId: createInternalInferenceId() } } : {}),
|
|
363
|
+
});
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
private async recordFailure(
|
|
368
|
+
attempt: InternalInferenceAttemptRecord,
|
|
369
|
+
leaseToken: string,
|
|
370
|
+
error: unknown,
|
|
371
|
+
meteringRecord: OperationMeteringRecord | null,
|
|
372
|
+
): Promise<void> {
|
|
373
|
+
const strategy = this.registry.get(attempt.purpose, attempt.input.strategyId, attempt.input.version);
|
|
374
|
+
const disposition = strategy?.classifyError(error) ?? { kind: "terminal" as const, code: "unknown_strategy" };
|
|
375
|
+
const canRetry = disposition.kind === "retryable"
|
|
376
|
+
&& attempt.attemptNumber < this.config.settings.retry.maxAttempts;
|
|
377
|
+
const delay = retryDelay(this.config.settings.retry.backoffMs, attempt.attemptNumber);
|
|
378
|
+
const failed = await this.config.persistence.transaction(async (persistence) => {
|
|
379
|
+
if (meteringRecord && attempt.agentConversationId) {
|
|
380
|
+
await persistence.metering.commit({
|
|
381
|
+
agentConversationId: attempt.agentConversationId,
|
|
382
|
+
record: meteringRecord,
|
|
383
|
+
meteringRecords: this.config.meteringRecords ?? "all",
|
|
384
|
+
});
|
|
385
|
+
} else if (meteringRecord) {
|
|
386
|
+
await persistence.metering.commitAgent({
|
|
387
|
+
agentSessionId: attempt.agentSessionId,
|
|
388
|
+
record: meteringRecord,
|
|
389
|
+
meteringRecords: this.config.meteringRecords ?? "all",
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
return await persistence.internalInferences!.fail({
|
|
393
|
+
internalInferenceId: attempt.internalInferenceId,
|
|
394
|
+
workerId: this.workerId,
|
|
395
|
+
leaseToken,
|
|
396
|
+
error: error instanceof Error ? error.message : String(error),
|
|
397
|
+
failureCode: disposition.code,
|
|
398
|
+
...(canRetry
|
|
399
|
+
? {
|
|
400
|
+
retry: {
|
|
401
|
+
internalInferenceId: createInternalInferenceId(),
|
|
402
|
+
nextAttemptAt: new Date(Date.now() + delay).toISOString(),
|
|
403
|
+
},
|
|
404
|
+
}
|
|
405
|
+
: {}),
|
|
406
|
+
});
|
|
407
|
+
});
|
|
408
|
+
this.publishAttempt(failed);
|
|
409
|
+
await this.refreshRun(attempt.rootInternalInferenceId);
|
|
410
|
+
if (!canRetry) await this.pruneTerminal();
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
private ownAttempt(record: InternalInferenceAttemptRecord): AttemptHandle {
|
|
414
|
+
let handle = this.attempts.get(record.internalInferenceId);
|
|
415
|
+
if (!handle) {
|
|
416
|
+
handle = new AttemptHandle(record, (reason) => this.cancel(record.rootInternalInferenceId, reason));
|
|
417
|
+
this.attempts.set(record.internalInferenceId, handle);
|
|
418
|
+
} else handle.update(record);
|
|
419
|
+
return handle;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
private ownRun(chain: InternalInferenceChainRecord, attempt: InternalInferenceAttemptRecord): RunHandle {
|
|
423
|
+
const ownedAttempt = this.ownAttempt(attempt);
|
|
424
|
+
let run = this.runs.get(chain.rootInternalInferenceId);
|
|
425
|
+
if (!run) {
|
|
426
|
+
run = new RunHandle(chain, ownedAttempt, (reason) => this.cancel(chain.rootInternalInferenceId, reason));
|
|
427
|
+
this.runs.set(chain.rootInternalInferenceId, run);
|
|
428
|
+
} else run.update(chain, ownedAttempt);
|
|
429
|
+
return run;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
private publishAttempt(record: InternalInferenceAttemptRecord): void {
|
|
433
|
+
const handle = this.ownAttempt(record);
|
|
434
|
+
const event: InternalInferenceEvent = {
|
|
435
|
+
kind: "changed",
|
|
436
|
+
sequence: ++this.eventSequence,
|
|
437
|
+
inferenceId: record.internalInferenceId,
|
|
438
|
+
rootId: record.rootInternalInferenceId,
|
|
439
|
+
revision: record.revision,
|
|
440
|
+
snapshot: handle.snapshot,
|
|
441
|
+
};
|
|
442
|
+
handle.emit(event);
|
|
443
|
+
this.hub.emit(event);
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
private publishProgress(id: InternalInferenceId, stage: InternalInferenceSnapshot["stage"]): void {
|
|
447
|
+
const handle = this.attempts.get(id);
|
|
448
|
+
if (!handle) return;
|
|
449
|
+
handle.setStage(stage);
|
|
450
|
+
const snapshot = handle.snapshot;
|
|
451
|
+
const event: InternalInferenceEvent = {
|
|
452
|
+
kind: "changed",
|
|
453
|
+
sequence: ++this.eventSequence,
|
|
454
|
+
inferenceId: id,
|
|
455
|
+
rootId: snapshot.rootId,
|
|
456
|
+
revision: snapshot.revision,
|
|
457
|
+
snapshot,
|
|
458
|
+
};
|
|
459
|
+
handle.emit(event);
|
|
460
|
+
this.hub.emit(event);
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
private async refreshRun(rootId: InternalInferenceId): Promise<void> {
|
|
464
|
+
const chain = await this.config.repository.getChain(rootId);
|
|
465
|
+
if (chain) await this.refreshChain(chain);
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
private async refreshChain(chain: InternalInferenceChainRecord): Promise<void> {
|
|
469
|
+
const id = chain.activeInternalInferenceId ?? chain.rootInternalInferenceId;
|
|
470
|
+
const attempt = await this.config.repository.getAttempt(id);
|
|
471
|
+
if (attempt) this.ownRun(chain, attempt).update(chain, this.ownAttempt(attempt));
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
private assertOpen(): void {
|
|
475
|
+
if (this.closed) throw new Error("internal inference manager is closed");
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
private async pruneTerminal(): Promise<void> {
|
|
479
|
+
const retention = this.config.settings.retention;
|
|
480
|
+
if (retention !== "all") await this.config.repository.pruneTerminal(retention.retain);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
function retryDelay(backoff: readonly number[], attemptNumber: number): number {
|
|
485
|
+
if (!backoff.length) return 0;
|
|
486
|
+
return backoff[Math.min(attemptNumber - 1, backoff.length - 1)] ?? 0;
|
|
487
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import type { InternalInferenceId } from "./contracts.ts";
|
|
3
|
+
|
|
4
|
+
export function createInternalInferenceId(): InternalInferenceId {
|
|
5
|
+
return `aii-${randomUUID()}`;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function isInternalInferenceId(value: unknown): value is InternalInferenceId {
|
|
9
|
+
return typeof value === "string" && /^aii-[0-9a-f-]{36}$/i.test(value);
|
|
10
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export * from "./contracts.ts";
|
|
2
|
+
export * from "./config.ts";
|
|
3
|
+
export * from "./ids.ts";
|
|
4
|
+
export { InternalInferenceStrategyRegistry } from "./strategy/registry.ts";
|
|
5
|
+
export { HarnessInternalInferenceRuntime } from "./runtime/harness-runtime.ts";
|
|
6
|
+
export type { HarnessInternalInferenceRuntimeConfig } from "./runtime/harness-runtime.ts";
|
|
7
|
+
export { DefaultInternalInferenceManager } from "./coordination/manager.ts";
|
|
8
|
+
export type { DefaultInternalInferenceManagerConfig } from "./coordination/manager.ts";
|
|
9
|
+
export type { InternalInferenceRepository } from "./persistence/repository.ts";
|
|
10
|
+
export type * from "./persistence/records.ts";
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import type { AgentConversationId, AgentSessionId } from "../../agent-ids.ts";
|
|
2
|
+
import type { PersistenceJsonValue } from "../../persistence/backend.ts";
|
|
3
|
+
import type {
|
|
4
|
+
InternalInferenceChainStatus,
|
|
5
|
+
InternalInferenceCompletion,
|
|
6
|
+
InternalInferenceId,
|
|
7
|
+
InternalInferenceInputDescriptor,
|
|
8
|
+
InternalInferencePurpose,
|
|
9
|
+
InternalInferenceStatus,
|
|
10
|
+
} from "../contracts.ts";
|
|
11
|
+
|
|
12
|
+
export interface InternalInferenceAttemptRecord {
|
|
13
|
+
readonly internalInferenceId: InternalInferenceId;
|
|
14
|
+
readonly rootInternalInferenceId: InternalInferenceId;
|
|
15
|
+
readonly retryOfInternalInferenceId?: InternalInferenceId;
|
|
16
|
+
readonly attemptNumber: number;
|
|
17
|
+
readonly agentSessionId: AgentSessionId;
|
|
18
|
+
readonly agentConversationId?: AgentConversationId;
|
|
19
|
+
readonly purpose: InternalInferencePurpose;
|
|
20
|
+
readonly status: InternalInferenceStatus;
|
|
21
|
+
readonly adapterId: string;
|
|
22
|
+
readonly executionProfileId?: string;
|
|
23
|
+
readonly input: InternalInferenceInputDescriptor;
|
|
24
|
+
readonly model?: string;
|
|
25
|
+
readonly internalSessionId?: string;
|
|
26
|
+
readonly sourceCheckpointId?: string;
|
|
27
|
+
readonly sourceFromSequence?: number;
|
|
28
|
+
readonly sourceThroughSequence?: number;
|
|
29
|
+
readonly requestedAt: string;
|
|
30
|
+
readonly startedAt?: string;
|
|
31
|
+
readonly completedAt?: string;
|
|
32
|
+
readonly nextAttemptAt?: string;
|
|
33
|
+
readonly workerId?: string;
|
|
34
|
+
readonly leaseToken?: string;
|
|
35
|
+
readonly leaseExpiresAt?: string;
|
|
36
|
+
readonly heartbeatAt?: string;
|
|
37
|
+
readonly revision: number;
|
|
38
|
+
readonly completion?: InternalInferenceCompletion;
|
|
39
|
+
readonly error?: string;
|
|
40
|
+
readonly failureCode?: string;
|
|
41
|
+
readonly meteringOperationId?: string;
|
|
42
|
+
readonly metadata?: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface InternalInferenceChainRecord {
|
|
46
|
+
readonly rootInternalInferenceId: InternalInferenceId;
|
|
47
|
+
readonly agentSessionId: AgentSessionId;
|
|
48
|
+
readonly agentConversationId?: AgentConversationId;
|
|
49
|
+
readonly purpose: InternalInferencePurpose;
|
|
50
|
+
readonly status: InternalInferenceChainStatus;
|
|
51
|
+
readonly activeInternalInferenceId?: InternalInferenceId;
|
|
52
|
+
readonly requestedThroughSequence?: number;
|
|
53
|
+
readonly revision: number;
|
|
54
|
+
readonly createdAt: string;
|
|
55
|
+
readonly updatedAt: string;
|
|
56
|
+
readonly error?: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface EnqueueInternalInferenceInput {
|
|
60
|
+
readonly internalInferenceId: InternalInferenceId;
|
|
61
|
+
readonly agentSessionId: AgentSessionId;
|
|
62
|
+
readonly agentConversationId?: AgentConversationId;
|
|
63
|
+
readonly purpose: InternalInferencePurpose;
|
|
64
|
+
readonly adapterId: string;
|
|
65
|
+
readonly executionProfileId?: string;
|
|
66
|
+
readonly input: InternalInferenceInputDescriptor;
|
|
67
|
+
readonly sourceCheckpointId?: string;
|
|
68
|
+
readonly sourceFromSequence?: number;
|
|
69
|
+
readonly sourceThroughSequence?: number;
|
|
70
|
+
readonly requestedThroughSequence?: number;
|
|
71
|
+
readonly requestedAt?: string;
|
|
72
|
+
readonly nextAttemptAt?: string;
|
|
73
|
+
readonly metadata?: string;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface ClaimInternalInferenceInput {
|
|
77
|
+
readonly workerId: string;
|
|
78
|
+
readonly leaseToken: string;
|
|
79
|
+
readonly leaseDurationMs: number;
|
|
80
|
+
readonly now?: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface ClaimedInternalInference {
|
|
84
|
+
readonly attempt: InternalInferenceAttemptRecord;
|
|
85
|
+
readonly chain: InternalInferenceChainRecord;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface InternalInferencePage {
|
|
89
|
+
readonly attempts: readonly InternalInferenceAttemptRecord[];
|
|
90
|
+
readonly nextCursor?: string;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface InternalInferenceRecordListOptions {
|
|
94
|
+
readonly agentConversationId?: AgentConversationId;
|
|
95
|
+
readonly purpose?: InternalInferencePurpose;
|
|
96
|
+
readonly status?: InternalInferenceStatus;
|
|
97
|
+
readonly rootId?: InternalInferenceId;
|
|
98
|
+
readonly limit?: number;
|
|
99
|
+
readonly cursor?: string;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export interface CompleteInternalInferenceInput {
|
|
103
|
+
readonly internalInferenceId: InternalInferenceId;
|
|
104
|
+
readonly workerId: string;
|
|
105
|
+
readonly leaseToken: string;
|
|
106
|
+
readonly completion: InternalInferenceCompletion;
|
|
107
|
+
readonly model?: string;
|
|
108
|
+
readonly internalSessionId: string;
|
|
109
|
+
readonly meteringOperationId?: string;
|
|
110
|
+
readonly completedAt?: string;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export interface FailInternalInferenceInput {
|
|
114
|
+
readonly internalInferenceId: InternalInferenceId;
|
|
115
|
+
readonly workerId: string;
|
|
116
|
+
readonly leaseToken: string;
|
|
117
|
+
readonly error: string;
|
|
118
|
+
readonly failureCode: string;
|
|
119
|
+
readonly retry?: {
|
|
120
|
+
readonly internalInferenceId: InternalInferenceId;
|
|
121
|
+
readonly nextAttemptAt?: string;
|
|
122
|
+
};
|
|
123
|
+
readonly completedAt?: string;
|
|
124
|
+
readonly resultMetadata?: PersistenceJsonValue;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export interface RecoverExpiredInternalInferenceInput {
|
|
128
|
+
readonly retryInternalInferenceId: InternalInferenceId;
|
|
129
|
+
readonly maxAttempts: number;
|
|
130
|
+
readonly nextAttemptAt?: string;
|
|
131
|
+
readonly now?: string;
|
|
132
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { InternalInferenceId } from "../contracts.ts";
|
|
2
|
+
import type {
|
|
3
|
+
ClaimInternalInferenceInput,
|
|
4
|
+
ClaimedInternalInference,
|
|
5
|
+
CompleteInternalInferenceInput,
|
|
6
|
+
EnqueueInternalInferenceInput,
|
|
7
|
+
FailInternalInferenceInput,
|
|
8
|
+
InternalInferenceAttemptRecord,
|
|
9
|
+
InternalInferenceChainRecord,
|
|
10
|
+
InternalInferenceRecordListOptions,
|
|
11
|
+
InternalInferencePage,
|
|
12
|
+
RecoverExpiredInternalInferenceInput,
|
|
13
|
+
} from "./records.ts";
|
|
14
|
+
|
|
15
|
+
export interface InternalInferenceRepository {
|
|
16
|
+
enqueue(input: EnqueueInternalInferenceInput): Promise<ClaimedInternalInference>;
|
|
17
|
+
claimNext(input: ClaimInternalInferenceInput): Promise<ClaimedInternalInference | null>;
|
|
18
|
+
heartbeat(
|
|
19
|
+
id: InternalInferenceId,
|
|
20
|
+
workerId: string,
|
|
21
|
+
leaseToken: string,
|
|
22
|
+
leaseDurationMs: number,
|
|
23
|
+
): Promise<InternalInferenceAttemptRecord | null>;
|
|
24
|
+
complete(input: CompleteInternalInferenceInput): Promise<InternalInferenceAttemptRecord>;
|
|
25
|
+
fail(input: FailInternalInferenceInput): Promise<InternalInferenceAttemptRecord>;
|
|
26
|
+
recoverExpired(
|
|
27
|
+
input: RecoverExpiredInternalInferenceInput,
|
|
28
|
+
): Promise<InternalInferenceAttemptRecord | null>;
|
|
29
|
+
cancel(rootId: InternalInferenceId, reason?: string): Promise<InternalInferenceChainRecord>;
|
|
30
|
+
getAttempt(id: InternalInferenceId): Promise<InternalInferenceAttemptRecord | null>;
|
|
31
|
+
getChain(rootId: InternalInferenceId): Promise<InternalInferenceChainRecord | null>;
|
|
32
|
+
list(options?: InternalInferenceRecordListOptions): Promise<InternalInferencePage>;
|
|
33
|
+
/** Keep the newest terminal runs and delete older complete retry lineages atomically. */
|
|
34
|
+
pruneTerminal(retainRuns: number): Promise<number>;
|
|
35
|
+
}
|