@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.
- package/CHANGELOG-audit.md +58 -0
- package/CONSUMER_GUIDE.md +474 -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 +1022 -682
- 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/controller.ts +37 -5
- package/src/identity.ts +62 -0
- package/src/index.ts +121 -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/managed-creation.ts +18 -2
- package/src/persistence/managed-load.ts +19 -5
- package/src/persistence/managed-open-progress.ts +54 -0
- package/src/persistence/presentation.ts +3 -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,551 @@
|
|
|
1
|
+
import type { Database } from "bun:sqlite";
|
|
2
|
+
import type { AgentConversationId, AgentSessionId } from "../../agent-ids.ts";
|
|
3
|
+
import { PersistenceConflictError } from "../../persistence/backend.ts";
|
|
4
|
+
import type {
|
|
5
|
+
InternalInferenceChainStatus,
|
|
6
|
+
InternalInferenceCompletion,
|
|
7
|
+
InternalInferenceId,
|
|
8
|
+
InternalInferenceInputDescriptor,
|
|
9
|
+
InternalInferencePurpose,
|
|
10
|
+
InternalInferenceStatus,
|
|
11
|
+
} from "../contracts.ts";
|
|
12
|
+
import type { InternalInferenceRepository } from "./repository.ts";
|
|
13
|
+
import type {
|
|
14
|
+
ClaimInternalInferenceInput,
|
|
15
|
+
ClaimedInternalInference,
|
|
16
|
+
CompleteInternalInferenceInput,
|
|
17
|
+
EnqueueInternalInferenceInput,
|
|
18
|
+
FailInternalInferenceInput,
|
|
19
|
+
InternalInferenceAttemptRecord,
|
|
20
|
+
InternalInferenceChainRecord,
|
|
21
|
+
InternalInferenceRecordListOptions,
|
|
22
|
+
InternalInferencePage,
|
|
23
|
+
RecoverExpiredInternalInferenceInput,
|
|
24
|
+
} from "./records.ts";
|
|
25
|
+
|
|
26
|
+
type WriteRunner = <T>(work: () => T) => Promise<T>;
|
|
27
|
+
|
|
28
|
+
interface AttemptRow {
|
|
29
|
+
internal_inference_id: string;
|
|
30
|
+
root_internal_inference_id: string;
|
|
31
|
+
retry_of_internal_inference_id: string | null;
|
|
32
|
+
attempt_number: number;
|
|
33
|
+
agent_session_id: string;
|
|
34
|
+
agent_conversation_id: string | null;
|
|
35
|
+
purpose: string;
|
|
36
|
+
status: string;
|
|
37
|
+
adapter_id: string;
|
|
38
|
+
execution_profile_id: string | null;
|
|
39
|
+
input_json: string;
|
|
40
|
+
model: string | null;
|
|
41
|
+
internal_session_id: string | null;
|
|
42
|
+
source_checkpoint_id: string | null;
|
|
43
|
+
source_from_sequence: number | null;
|
|
44
|
+
source_through_sequence: number | null;
|
|
45
|
+
requested_at: string;
|
|
46
|
+
started_at: string | null;
|
|
47
|
+
completed_at: string | null;
|
|
48
|
+
next_attempt_at: string | null;
|
|
49
|
+
worker_id: string | null;
|
|
50
|
+
lease_token: string | null;
|
|
51
|
+
lease_expires_at: string | null;
|
|
52
|
+
heartbeat_at: string | null;
|
|
53
|
+
revision: number;
|
|
54
|
+
result_json: string | null;
|
|
55
|
+
error: string | null;
|
|
56
|
+
failure_code: string | null;
|
|
57
|
+
metering_operation_id: string | null;
|
|
58
|
+
metadata: string | null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
interface ChainRow {
|
|
62
|
+
root_internal_inference_id: string;
|
|
63
|
+
agent_session_id: string;
|
|
64
|
+
agent_conversation_id: string | null;
|
|
65
|
+
purpose: string;
|
|
66
|
+
status: string;
|
|
67
|
+
active_internal_inference_id: string | null;
|
|
68
|
+
requested_through_sequence: number | null;
|
|
69
|
+
revision: number;
|
|
70
|
+
created_at: string;
|
|
71
|
+
updated_at: string;
|
|
72
|
+
error: string | null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** SQLite implementation kept outside the general backend to preserve feature ownership. */
|
|
76
|
+
export class SqliteInternalInferenceRepository implements InternalInferenceRepository {
|
|
77
|
+
constructor(
|
|
78
|
+
private readonly database: Database,
|
|
79
|
+
private readonly runWrite: WriteRunner,
|
|
80
|
+
) {}
|
|
81
|
+
|
|
82
|
+
async enqueue(input: EnqueueInternalInferenceInput): Promise<ClaimedInternalInference> {
|
|
83
|
+
return await this.runWrite(() => {
|
|
84
|
+
const now = input.requestedAt ?? databaseNow(this.database);
|
|
85
|
+
const active = input.purpose === "conversation_checkpoint"
|
|
86
|
+
? this.database.query<ChainRow, [string, string, string]>(
|
|
87
|
+
`SELECT * FROM internal_inference_chains
|
|
88
|
+
WHERE agent_session_id = ? AND COALESCE(agent_conversation_id, '') = ?
|
|
89
|
+
AND purpose = ? AND status = 'active'`,
|
|
90
|
+
).get(input.agentSessionId, input.agentConversationId ?? "", input.purpose)
|
|
91
|
+
: null;
|
|
92
|
+
if (active) {
|
|
93
|
+
if (input.requestedThroughSequence !== undefined) {
|
|
94
|
+
this.database.query(
|
|
95
|
+
`UPDATE internal_inference_chains SET
|
|
96
|
+
requested_through_sequence = MAX(COALESCE(requested_through_sequence, 0), ?),
|
|
97
|
+
revision = revision + 1, updated_at = ?
|
|
98
|
+
WHERE root_internal_inference_id = ? AND status = 'active'`,
|
|
99
|
+
).run(input.requestedThroughSequence, now, active.root_internal_inference_id);
|
|
100
|
+
}
|
|
101
|
+
return this.requireClaimed(active.active_internal_inference_id!);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
this.database.query(
|
|
105
|
+
`INSERT INTO internal_inference_chains(
|
|
106
|
+
root_internal_inference_id, agent_session_id, agent_conversation_id, purpose,
|
|
107
|
+
status, active_internal_inference_id, requested_through_sequence,
|
|
108
|
+
revision, created_at, updated_at
|
|
109
|
+
) VALUES (?, ?, ?, ?, 'active', ?, ?, 1, ?, ?)`,
|
|
110
|
+
).run(
|
|
111
|
+
input.internalInferenceId,
|
|
112
|
+
input.agentSessionId,
|
|
113
|
+
input.agentConversationId ?? null,
|
|
114
|
+
input.purpose,
|
|
115
|
+
input.internalInferenceId,
|
|
116
|
+
input.requestedThroughSequence ?? null,
|
|
117
|
+
now,
|
|
118
|
+
now,
|
|
119
|
+
);
|
|
120
|
+
this.database.query(
|
|
121
|
+
`INSERT INTO internal_inferences(
|
|
122
|
+
internal_inference_id, root_internal_inference_id, attempt_number,
|
|
123
|
+
agent_session_id, agent_conversation_id, purpose, status, adapter_id,
|
|
124
|
+
execution_profile_id, input_json, source_checkpoint_id, source_from_sequence,
|
|
125
|
+
source_through_sequence, requested_at, next_attempt_at, revision, metadata
|
|
126
|
+
) VALUES (?, ?, 1, ?, ?, ?, 'queued', ?, ?, ?, ?, ?, ?, ?, ?, 1, ?)`,
|
|
127
|
+
).run(
|
|
128
|
+
input.internalInferenceId,
|
|
129
|
+
input.internalInferenceId,
|
|
130
|
+
input.agentSessionId,
|
|
131
|
+
input.agentConversationId ?? null,
|
|
132
|
+
input.purpose,
|
|
133
|
+
input.adapterId,
|
|
134
|
+
input.executionProfileId ?? null,
|
|
135
|
+
JSON.stringify(input.input),
|
|
136
|
+
input.sourceCheckpointId ?? null,
|
|
137
|
+
input.sourceFromSequence ?? null,
|
|
138
|
+
input.sourceThroughSequence ?? null,
|
|
139
|
+
now,
|
|
140
|
+
input.nextAttemptAt ?? null,
|
|
141
|
+
input.metadata ?? null,
|
|
142
|
+
);
|
|
143
|
+
return this.requireClaimed(input.internalInferenceId);
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async claimNext(input: ClaimInternalInferenceInput): Promise<ClaimedInternalInference | null> {
|
|
148
|
+
return await this.runWrite(() => {
|
|
149
|
+
const now = input.now ?? databaseNow(this.database);
|
|
150
|
+
const row = this.database.query<AttemptRow, [string]>(
|
|
151
|
+
`SELECT i.* FROM internal_inferences i
|
|
152
|
+
JOIN internal_inference_chains c
|
|
153
|
+
ON c.root_internal_inference_id = i.root_internal_inference_id
|
|
154
|
+
WHERE i.status = 'queued' AND c.status = 'active'
|
|
155
|
+
AND (i.next_attempt_at IS NULL OR i.next_attempt_at <= ?)
|
|
156
|
+
ORDER BY COALESCE(i.next_attempt_at, i.requested_at), i.requested_at,
|
|
157
|
+
i.internal_inference_id LIMIT 1`,
|
|
158
|
+
).get(now);
|
|
159
|
+
if (!row) return null;
|
|
160
|
+
const expiresAt = new Date(Date.parse(now) + input.leaseDurationMs).toISOString();
|
|
161
|
+
const changed = this.database.query(
|
|
162
|
+
`UPDATE internal_inferences SET status = 'running', worker_id = ?, lease_token = ?,
|
|
163
|
+
lease_expires_at = ?, heartbeat_at = ?, started_at = COALESCE(started_at, ?),
|
|
164
|
+
revision = revision + 1
|
|
165
|
+
WHERE internal_inference_id = ? AND status = 'queued' AND revision = ?`,
|
|
166
|
+
).run(
|
|
167
|
+
input.workerId,
|
|
168
|
+
input.leaseToken,
|
|
169
|
+
expiresAt,
|
|
170
|
+
now,
|
|
171
|
+
now,
|
|
172
|
+
row.internal_inference_id,
|
|
173
|
+
row.revision,
|
|
174
|
+
);
|
|
175
|
+
if (changed.changes !== 1) return null;
|
|
176
|
+
return this.requireClaimed(row.internal_inference_id);
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async heartbeat(
|
|
181
|
+
id: InternalInferenceId,
|
|
182
|
+
workerId: string,
|
|
183
|
+
leaseToken: string,
|
|
184
|
+
leaseDurationMs: number,
|
|
185
|
+
): Promise<InternalInferenceAttemptRecord | null> {
|
|
186
|
+
return await this.runWrite(() => {
|
|
187
|
+
const now = databaseNow(this.database);
|
|
188
|
+
const expiresAt = new Date(Date.parse(now) + leaseDurationMs).toISOString();
|
|
189
|
+
const changed = this.database.query(
|
|
190
|
+
`UPDATE internal_inferences SET heartbeat_at = ?, lease_expires_at = ?, revision = revision + 1
|
|
191
|
+
WHERE internal_inference_id = ? AND status = 'running'
|
|
192
|
+
AND worker_id = ? AND lease_token = ? AND lease_expires_at > ?`,
|
|
193
|
+
).run(now, expiresAt, id, workerId, leaseToken, now);
|
|
194
|
+
return changed.changes === 1 ? this.getAttemptSync(id) : null;
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async complete(input: CompleteInternalInferenceInput): Promise<InternalInferenceAttemptRecord> {
|
|
199
|
+
return await this.runWrite(() => {
|
|
200
|
+
const now = input.completedAt ?? databaseNow(this.database);
|
|
201
|
+
const row = this.requireOwnedRunning(input.internalInferenceId, input.workerId, input.leaseToken, now);
|
|
202
|
+
const changed = this.database.query(
|
|
203
|
+
`UPDATE internal_inferences SET status = 'completed', completed_at = ?, model = ?,
|
|
204
|
+
internal_session_id = ?, result_json = ?, metering_operation_id = ?,
|
|
205
|
+
worker_id = NULL, lease_token = NULL, lease_expires_at = NULL,
|
|
206
|
+
revision = revision + 1
|
|
207
|
+
WHERE internal_inference_id = ? AND status = 'running'
|
|
208
|
+
AND worker_id = ? AND lease_token = ?`,
|
|
209
|
+
).run(
|
|
210
|
+
now,
|
|
211
|
+
input.model ?? null,
|
|
212
|
+
input.internalSessionId,
|
|
213
|
+
JSON.stringify(input.completion),
|
|
214
|
+
input.meteringOperationId ?? null,
|
|
215
|
+
input.internalInferenceId,
|
|
216
|
+
input.workerId,
|
|
217
|
+
input.leaseToken,
|
|
218
|
+
);
|
|
219
|
+
if (changed.changes !== 1) throw lostLease(input.internalInferenceId);
|
|
220
|
+
this.database.query(
|
|
221
|
+
`UPDATE internal_inference_chains SET status = 'completed',
|
|
222
|
+
revision = revision + 1, updated_at = ?
|
|
223
|
+
WHERE root_internal_inference_id = ? AND status = 'active'
|
|
224
|
+
AND active_internal_inference_id = ?`,
|
|
225
|
+
).run(now, row.root_internal_inference_id, input.internalInferenceId);
|
|
226
|
+
return this.getAttemptSync(input.internalInferenceId)!;
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async fail(input: FailInternalInferenceInput): Promise<InternalInferenceAttemptRecord> {
|
|
231
|
+
return await this.runWrite(() => {
|
|
232
|
+
const now = input.completedAt ?? databaseNow(this.database);
|
|
233
|
+
const row = this.requireOwnedRunning(input.internalInferenceId, input.workerId, input.leaseToken, now);
|
|
234
|
+
this.database.query(
|
|
235
|
+
`UPDATE internal_inferences SET status = 'failed', completed_at = ?, error = ?,
|
|
236
|
+
failure_code = ?, result_json = ?, worker_id = NULL, lease_token = NULL,
|
|
237
|
+
lease_expires_at = NULL, revision = revision + 1
|
|
238
|
+
WHERE internal_inference_id = ? AND status = 'running'
|
|
239
|
+
AND worker_id = ? AND lease_token = ?`,
|
|
240
|
+
).run(
|
|
241
|
+
now,
|
|
242
|
+
input.error,
|
|
243
|
+
input.failureCode,
|
|
244
|
+
input.resultMetadata === undefined ? null : JSON.stringify(input.resultMetadata),
|
|
245
|
+
input.internalInferenceId,
|
|
246
|
+
input.workerId,
|
|
247
|
+
input.leaseToken,
|
|
248
|
+
);
|
|
249
|
+
if (input.retry) {
|
|
250
|
+
this.database.query(
|
|
251
|
+
`INSERT INTO internal_inferences(
|
|
252
|
+
internal_inference_id, root_internal_inference_id, retry_of_internal_inference_id,
|
|
253
|
+
attempt_number, agent_session_id, agent_conversation_id, purpose, status,
|
|
254
|
+
adapter_id, execution_profile_id, input_json, source_checkpoint_id,
|
|
255
|
+
source_from_sequence, source_through_sequence, requested_at, next_attempt_at,
|
|
256
|
+
revision, metadata
|
|
257
|
+
) SELECT ?, root_internal_inference_id, internal_inference_id, attempt_number + 1,
|
|
258
|
+
agent_session_id, agent_conversation_id, purpose, 'queued', adapter_id,
|
|
259
|
+
execution_profile_id, input_json, source_checkpoint_id, source_from_sequence,
|
|
260
|
+
source_through_sequence, ?, ?, 1, metadata
|
|
261
|
+
FROM internal_inferences WHERE internal_inference_id = ?`,
|
|
262
|
+
).run(input.retry.internalInferenceId, now, input.retry.nextAttemptAt ?? null, input.internalInferenceId);
|
|
263
|
+
this.database.query(
|
|
264
|
+
`UPDATE internal_inference_chains SET active_internal_inference_id = ?,
|
|
265
|
+
revision = revision + 1, updated_at = ?, error = NULL
|
|
266
|
+
WHERE root_internal_inference_id = ? AND status = 'active'
|
|
267
|
+
AND active_internal_inference_id = ?`,
|
|
268
|
+
).run(input.retry.internalInferenceId, now, row.root_internal_inference_id, input.internalInferenceId);
|
|
269
|
+
} else {
|
|
270
|
+
this.database.query(
|
|
271
|
+
`UPDATE internal_inference_chains SET status = 'failed',
|
|
272
|
+
revision = revision + 1,
|
|
273
|
+
updated_at = ?, error = ?
|
|
274
|
+
WHERE root_internal_inference_id = ? AND status = 'active'
|
|
275
|
+
AND active_internal_inference_id = ?`,
|
|
276
|
+
).run(now, input.error, row.root_internal_inference_id, input.internalInferenceId);
|
|
277
|
+
}
|
|
278
|
+
return this.getAttemptSync(input.internalInferenceId)!;
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
async cancel(rootId: InternalInferenceId, reason = "cancelled by consumer"): Promise<InternalInferenceChainRecord> {
|
|
283
|
+
return await this.runWrite(() => {
|
|
284
|
+
const now = databaseNow(this.database);
|
|
285
|
+
this.database.query(
|
|
286
|
+
`UPDATE internal_inferences SET status = 'cancelled', completed_at = ?, error = ?,
|
|
287
|
+
failure_code = 'consumer_cancelled', worker_id = NULL, lease_token = NULL,
|
|
288
|
+
lease_expires_at = NULL, revision = revision + 1
|
|
289
|
+
WHERE root_internal_inference_id = ? AND status IN ('queued', 'running')`,
|
|
290
|
+
).run(now, reason, rootId);
|
|
291
|
+
const changed = this.database.query(
|
|
292
|
+
`UPDATE internal_inference_chains SET status = 'cancelled',
|
|
293
|
+
revision = revision + 1,
|
|
294
|
+
updated_at = ?, error = ?
|
|
295
|
+
WHERE root_internal_inference_id = ? AND status = 'active'`,
|
|
296
|
+
).run(now, reason, rootId);
|
|
297
|
+
if (changed.changes !== 1) throw new PersistenceConflictError(`internal inference run is not active: ${rootId}`);
|
|
298
|
+
return this.getChainSync(rootId)!;
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
async recoverExpired(
|
|
303
|
+
input: RecoverExpiredInternalInferenceInput,
|
|
304
|
+
): Promise<InternalInferenceAttemptRecord | null> {
|
|
305
|
+
return await this.runWrite(() => {
|
|
306
|
+
const now = input.now ?? databaseNow(this.database);
|
|
307
|
+
const row = this.database.query<AttemptRow, [string]>(
|
|
308
|
+
`SELECT * FROM internal_inferences
|
|
309
|
+
WHERE status = 'running' AND lease_expires_at <= ?
|
|
310
|
+
ORDER BY lease_expires_at, internal_inference_id LIMIT 1`,
|
|
311
|
+
).get(now);
|
|
312
|
+
if (!row) return null;
|
|
313
|
+
const retry = row.attempt_number < input.maxAttempts;
|
|
314
|
+
const changed = this.database.query(
|
|
315
|
+
`UPDATE internal_inferences SET status = 'failed', completed_at = ?,
|
|
316
|
+
error = 'worker lease expired', failure_code = 'lease_expired',
|
|
317
|
+
worker_id = NULL, lease_token = NULL, lease_expires_at = NULL,
|
|
318
|
+
revision = revision + 1
|
|
319
|
+
WHERE internal_inference_id = ? AND status = 'running'
|
|
320
|
+
AND lease_token = ? AND lease_expires_at <= ?`,
|
|
321
|
+
).run(now, row.internal_inference_id, row.lease_token, now);
|
|
322
|
+
if (changed.changes !== 1) return null;
|
|
323
|
+
if (retry) {
|
|
324
|
+
this.database.query(
|
|
325
|
+
`INSERT INTO internal_inferences(
|
|
326
|
+
internal_inference_id, root_internal_inference_id, retry_of_internal_inference_id,
|
|
327
|
+
attempt_number, agent_session_id, agent_conversation_id, purpose, status,
|
|
328
|
+
adapter_id, execution_profile_id, input_json, source_checkpoint_id,
|
|
329
|
+
source_from_sequence, source_through_sequence, requested_at, next_attempt_at,
|
|
330
|
+
revision, metadata
|
|
331
|
+
) SELECT ?, root_internal_inference_id, internal_inference_id, attempt_number + 1,
|
|
332
|
+
agent_session_id, agent_conversation_id, purpose, 'queued', adapter_id,
|
|
333
|
+
execution_profile_id, input_json, source_checkpoint_id, source_from_sequence,
|
|
334
|
+
source_through_sequence, ?, ?, 1, metadata
|
|
335
|
+
FROM internal_inferences WHERE internal_inference_id = ?`,
|
|
336
|
+
).run(input.retryInternalInferenceId, now, input.nextAttemptAt ?? null, row.internal_inference_id);
|
|
337
|
+
this.database.query(
|
|
338
|
+
`UPDATE internal_inference_chains SET active_internal_inference_id = ?,
|
|
339
|
+
revision = revision + 1, updated_at = ?, error = NULL
|
|
340
|
+
WHERE root_internal_inference_id = ? AND status = 'active'
|
|
341
|
+
AND active_internal_inference_id = ?`,
|
|
342
|
+
).run(
|
|
343
|
+
input.retryInternalInferenceId,
|
|
344
|
+
now,
|
|
345
|
+
row.root_internal_inference_id,
|
|
346
|
+
row.internal_inference_id,
|
|
347
|
+
);
|
|
348
|
+
} else {
|
|
349
|
+
this.database.query(
|
|
350
|
+
`UPDATE internal_inference_chains SET status = 'failed', revision = revision + 1,
|
|
351
|
+
updated_at = ?, error = 'worker lease expired'
|
|
352
|
+
WHERE root_internal_inference_id = ? AND status = 'active'
|
|
353
|
+
AND active_internal_inference_id = ?`,
|
|
354
|
+
).run(now, row.root_internal_inference_id, row.internal_inference_id);
|
|
355
|
+
}
|
|
356
|
+
return this.getAttemptSync(row.internal_inference_id as InternalInferenceId);
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
async getAttempt(id: InternalInferenceId): Promise<InternalInferenceAttemptRecord | null> {
|
|
361
|
+
return this.getAttemptSync(id);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
async getChain(rootId: InternalInferenceId): Promise<InternalInferenceChainRecord | null> {
|
|
365
|
+
return this.getChainSync(rootId);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
async list(options: InternalInferenceRecordListOptions = {}): Promise<InternalInferencePage> {
|
|
369
|
+
const limit = boundedLimit(options.limit ?? 100);
|
|
370
|
+
const cursor = options.cursor ? decodeCursor(options.cursor) : undefined;
|
|
371
|
+
const clauses: string[] = [];
|
|
372
|
+
const values: Array<string | number> = [];
|
|
373
|
+
if (options.agentConversationId) {
|
|
374
|
+
clauses.push("agent_conversation_id = ?");
|
|
375
|
+
values.push(options.agentConversationId);
|
|
376
|
+
}
|
|
377
|
+
if (options.purpose) {
|
|
378
|
+
clauses.push("purpose = ?");
|
|
379
|
+
values.push(options.purpose);
|
|
380
|
+
}
|
|
381
|
+
if (options.status) {
|
|
382
|
+
clauses.push("status = ?");
|
|
383
|
+
values.push(options.status);
|
|
384
|
+
}
|
|
385
|
+
if (options.rootId) {
|
|
386
|
+
clauses.push("root_internal_inference_id = ?");
|
|
387
|
+
values.push(options.rootId);
|
|
388
|
+
}
|
|
389
|
+
if (cursor) {
|
|
390
|
+
clauses.push("(requested_at < ? OR (requested_at = ? AND internal_inference_id < ?))");
|
|
391
|
+
values.push(cursor.requestedAt, cursor.requestedAt, cursor.id);
|
|
392
|
+
}
|
|
393
|
+
const where = clauses.length ? `WHERE ${clauses.join(" AND ")}` : "";
|
|
394
|
+
const rows = this.database.query<AttemptRow, Array<string | number>>(
|
|
395
|
+
`SELECT * FROM internal_inferences ${where}
|
|
396
|
+
ORDER BY requested_at DESC, internal_inference_id DESC LIMIT ?`,
|
|
397
|
+
).all(...values, limit + 1);
|
|
398
|
+
const page = rows.slice(0, limit);
|
|
399
|
+
const last = page.at(-1);
|
|
400
|
+
return {
|
|
401
|
+
attempts: Object.freeze(page.map(attemptFromRow)),
|
|
402
|
+
...(rows.length > limit && last
|
|
403
|
+
? { nextCursor: encodeCursor(last.requested_at, last.internal_inference_id) }
|
|
404
|
+
: {}),
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
async pruneTerminal(retainRuns: number): Promise<number> {
|
|
409
|
+
if (!Number.isSafeInteger(retainRuns) || retainRuns < 0) {
|
|
410
|
+
throw new Error("internal inference retention must be a non-negative integer");
|
|
411
|
+
}
|
|
412
|
+
return await this.runWrite(() => {
|
|
413
|
+
const roots = this.database.query<{ root_internal_inference_id: string }, [number]>(
|
|
414
|
+
`SELECT root_internal_inference_id FROM internal_inference_chains
|
|
415
|
+
WHERE status IN ('completed', 'failed', 'cancelled')
|
|
416
|
+
ORDER BY updated_at DESC, root_internal_inference_id DESC
|
|
417
|
+
LIMIT -1 OFFSET ?`,
|
|
418
|
+
).all(retainRuns).map((row) => row.root_internal_inference_id);
|
|
419
|
+
if (!roots.length) return 0;
|
|
420
|
+
const placeholders = roots.map(() => "?").join(", ");
|
|
421
|
+
this.database.query(`DELETE FROM internal_inferences WHERE root_internal_inference_id IN (${placeholders})`)
|
|
422
|
+
.run(...roots);
|
|
423
|
+
this.database.query(`DELETE FROM internal_inference_chains WHERE root_internal_inference_id IN (${placeholders})`)
|
|
424
|
+
.run(...roots);
|
|
425
|
+
return roots.length;
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
private requireClaimed(id: string): ClaimedInternalInference {
|
|
430
|
+
const attempt = this.getAttemptSync(id as InternalInferenceId);
|
|
431
|
+
if (!attempt) throw new Error(`internal inference attempt disappeared: ${id}`);
|
|
432
|
+
const chain = this.getChainSync(attempt.rootInternalInferenceId);
|
|
433
|
+
if (!chain) throw new Error(`internal inference chain disappeared: ${attempt.rootInternalInferenceId}`);
|
|
434
|
+
return { attempt, chain };
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
private requireOwnedRunning(id: InternalInferenceId, workerId: string, leaseToken: string, now: string): AttemptRow {
|
|
438
|
+
const row = this.database.query<AttemptRow, [string, string, string, string]>(
|
|
439
|
+
`SELECT * FROM internal_inferences WHERE internal_inference_id = ?
|
|
440
|
+
AND status = 'running' AND worker_id = ? AND lease_token = ? AND lease_expires_at > ?`,
|
|
441
|
+
).get(id, workerId, leaseToken, now);
|
|
442
|
+
if (!row) throw lostLease(id);
|
|
443
|
+
return row;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
private getAttemptSync(id: InternalInferenceId): InternalInferenceAttemptRecord | null {
|
|
447
|
+
const row = this.database.query<AttemptRow, [string]>(
|
|
448
|
+
"SELECT * FROM internal_inferences WHERE internal_inference_id = ?",
|
|
449
|
+
).get(id);
|
|
450
|
+
return row ? attemptFromRow(row) : null;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
private getChainSync(rootId: InternalInferenceId): InternalInferenceChainRecord | null {
|
|
454
|
+
const row = this.database.query<ChainRow, [string]>(
|
|
455
|
+
"SELECT * FROM internal_inference_chains WHERE root_internal_inference_id = ?",
|
|
456
|
+
).get(rootId);
|
|
457
|
+
return row ? chainFromRow(row) : null;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
function attemptFromRow(row: AttemptRow): InternalInferenceAttemptRecord {
|
|
462
|
+
return Object.freeze({
|
|
463
|
+
internalInferenceId: row.internal_inference_id as InternalInferenceId,
|
|
464
|
+
rootInternalInferenceId: row.root_internal_inference_id as InternalInferenceId,
|
|
465
|
+
...(row.retry_of_internal_inference_id
|
|
466
|
+
? { retryOfInternalInferenceId: row.retry_of_internal_inference_id as InternalInferenceId }
|
|
467
|
+
: {}),
|
|
468
|
+
attemptNumber: row.attempt_number,
|
|
469
|
+
agentSessionId: row.agent_session_id as AgentSessionId,
|
|
470
|
+
...(row.agent_conversation_id ? { agentConversationId: row.agent_conversation_id as AgentConversationId } : {}),
|
|
471
|
+
purpose: row.purpose as InternalInferencePurpose,
|
|
472
|
+
status: row.status as InternalInferenceStatus,
|
|
473
|
+
adapterId: row.adapter_id,
|
|
474
|
+
...(row.execution_profile_id ? { executionProfileId: row.execution_profile_id } : {}),
|
|
475
|
+
input: JSON.parse(row.input_json) as InternalInferenceInputDescriptor,
|
|
476
|
+
...(row.model ? { model: row.model } : {}),
|
|
477
|
+
...(row.internal_session_id ? { internalSessionId: row.internal_session_id } : {}),
|
|
478
|
+
...(row.source_checkpoint_id ? { sourceCheckpointId: row.source_checkpoint_id } : {}),
|
|
479
|
+
...(row.source_from_sequence === null ? {} : { sourceFromSequence: row.source_from_sequence }),
|
|
480
|
+
...(row.source_through_sequence === null ? {} : { sourceThroughSequence: row.source_through_sequence }),
|
|
481
|
+
requestedAt: row.requested_at,
|
|
482
|
+
...(row.started_at ? { startedAt: row.started_at } : {}),
|
|
483
|
+
...(row.completed_at ? { completedAt: row.completed_at } : {}),
|
|
484
|
+
...(row.next_attempt_at ? { nextAttemptAt: row.next_attempt_at } : {}),
|
|
485
|
+
...(row.worker_id ? { workerId: row.worker_id } : {}),
|
|
486
|
+
...(row.lease_token ? { leaseToken: row.lease_token } : {}),
|
|
487
|
+
...(row.lease_expires_at ? { leaseExpiresAt: row.lease_expires_at } : {}),
|
|
488
|
+
...(row.heartbeat_at ? { heartbeatAt: row.heartbeat_at } : {}),
|
|
489
|
+
revision: row.revision,
|
|
490
|
+
...(row.result_json && row.status === "completed"
|
|
491
|
+
? { completion: JSON.parse(row.result_json) as InternalInferenceCompletion }
|
|
492
|
+
: {}),
|
|
493
|
+
...(row.error ? { error: row.error } : {}),
|
|
494
|
+
...(row.failure_code ? { failureCode: row.failure_code } : {}),
|
|
495
|
+
...(row.metering_operation_id ? { meteringOperationId: row.metering_operation_id } : {}),
|
|
496
|
+
...(row.metadata ? { metadata: row.metadata } : {}),
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
function chainFromRow(row: ChainRow): InternalInferenceChainRecord {
|
|
501
|
+
return Object.freeze({
|
|
502
|
+
rootInternalInferenceId: row.root_internal_inference_id as InternalInferenceId,
|
|
503
|
+
agentSessionId: row.agent_session_id as AgentSessionId,
|
|
504
|
+
...(row.agent_conversation_id ? { agentConversationId: row.agent_conversation_id as AgentConversationId } : {}),
|
|
505
|
+
purpose: row.purpose as InternalInferencePurpose,
|
|
506
|
+
status: row.status as InternalInferenceChainStatus,
|
|
507
|
+
...(row.active_internal_inference_id
|
|
508
|
+
? { activeInternalInferenceId: row.active_internal_inference_id as InternalInferenceId }
|
|
509
|
+
: {}),
|
|
510
|
+
...(row.requested_through_sequence === null ? {} : { requestedThroughSequence: row.requested_through_sequence }),
|
|
511
|
+
revision: row.revision,
|
|
512
|
+
createdAt: row.created_at,
|
|
513
|
+
updatedAt: row.updated_at,
|
|
514
|
+
...(row.error ? { error: row.error } : {}),
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
function databaseNow(database: Database): string {
|
|
519
|
+
const row = database.query<{ now: string }, []>(
|
|
520
|
+
"SELECT strftime('%Y-%m-%dT%H:%M:%fZ', 'now') AS now",
|
|
521
|
+
).get();
|
|
522
|
+
if (!row) throw new Error("SQLite did not provide a current timestamp");
|
|
523
|
+
return row.now;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
function lostLease(id: InternalInferenceId): PersistenceConflictError {
|
|
527
|
+
return new PersistenceConflictError(`internal inference lease is no longer owned: ${id}`);
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
function boundedLimit(value: number): number {
|
|
531
|
+
if (!Number.isSafeInteger(value) || value < 1 || value > 1_000) {
|
|
532
|
+
throw new Error("internal inference list limit must be between 1 and 1000");
|
|
533
|
+
}
|
|
534
|
+
return value;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
function encodeCursor(requestedAt: string, id: string): string {
|
|
538
|
+
return Buffer.from(JSON.stringify({ requestedAt, id }), "utf8").toString("base64url");
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
function decodeCursor(value: string): { requestedAt: string; id: string } {
|
|
542
|
+
try {
|
|
543
|
+
const decoded = JSON.parse(Buffer.from(value, "base64url").toString("utf8")) as unknown;
|
|
544
|
+
if (!decoded || typeof decoded !== "object") throw new Error();
|
|
545
|
+
const record = decoded as Record<string, unknown>;
|
|
546
|
+
if (typeof record.requestedAt !== "string" || typeof record.id !== "string") throw new Error();
|
|
547
|
+
return { requestedAt: record.requestedAt, id: record.id };
|
|
548
|
+
} catch {
|
|
549
|
+
throw new Error("invalid internal inference cursor");
|
|
550
|
+
}
|
|
551
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { AgentController, type AgentControllerConfig } from "../../controller.ts";
|
|
2
|
+
import type { PromptResult } from "../../types.ts";
|
|
3
|
+
import type {
|
|
4
|
+
InternalInferenceRequest,
|
|
5
|
+
InternalInferenceResult,
|
|
6
|
+
InternalInferenceRuntime,
|
|
7
|
+
InternalInferenceRuntimeLifecycle,
|
|
8
|
+
} from "../contracts.ts";
|
|
9
|
+
|
|
10
|
+
export interface HarnessInternalInferenceRuntimeConfig {
|
|
11
|
+
controllerConfig(request: InternalInferenceRequest): AgentControllerConfig;
|
|
12
|
+
/** Test/custom seam; production defaults to AgentController. */
|
|
13
|
+
createController?(config: AgentControllerConfig): InternalInferenceController;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface InternalInferenceController {
|
|
17
|
+
startFresh(): Promise<{ sessionId: string }>;
|
|
18
|
+
prompt(text: string): Promise<PromptResult>;
|
|
19
|
+
interrupt(): void;
|
|
20
|
+
stop(): Promise<void>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Executes one internal inference in a fresh, disposable ACP provider session. */
|
|
24
|
+
export class HarnessInternalInferenceRuntime implements InternalInferenceRuntime {
|
|
25
|
+
constructor(private readonly config: HarnessInternalInferenceRuntimeConfig) {}
|
|
26
|
+
|
|
27
|
+
async run(
|
|
28
|
+
request: InternalInferenceRequest,
|
|
29
|
+
signal?: AbortSignal,
|
|
30
|
+
lifecycle?: InternalInferenceRuntimeLifecycle,
|
|
31
|
+
): Promise<InternalInferenceResult> {
|
|
32
|
+
const inherited = this.config.controllerConfig(request);
|
|
33
|
+
const controllerConfig: AgentControllerConfig = {
|
|
34
|
+
...inherited,
|
|
35
|
+
adapterId: request.adapterId,
|
|
36
|
+
cwd: request.cwd ?? inherited.cwd,
|
|
37
|
+
mode: "normal",
|
|
38
|
+
mcpServers: [],
|
|
39
|
+
defaultPermission: "cancel",
|
|
40
|
+
clientHandlers: {},
|
|
41
|
+
};
|
|
42
|
+
const controller = this.config.createController?.(controllerConfig)
|
|
43
|
+
?? new AgentController(controllerConfig);
|
|
44
|
+
const abort = () => controller.interrupt();
|
|
45
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
46
|
+
try {
|
|
47
|
+
if (signal?.aborted) throw abortError();
|
|
48
|
+
lifecycle?.stageChanged?.("creating_session");
|
|
49
|
+
const connection = await controller.startFresh();
|
|
50
|
+
await lifecycle?.sessionStarted({ internalSessionId: connection.sessionId, model: null });
|
|
51
|
+
if (signal?.aborted) throw abortError();
|
|
52
|
+
lifecycle?.stageChanged?.("prompting");
|
|
53
|
+
const result = await controller.prompt(request.prompt);
|
|
54
|
+
if (result.status !== "completed") {
|
|
55
|
+
throw new Error(`internal inference prompt ${result.status}: ${result.stopReason}`);
|
|
56
|
+
}
|
|
57
|
+
return Object.freeze({
|
|
58
|
+
internalInferenceId: request.internalInferenceId,
|
|
59
|
+
internalSessionId: connection.sessionId,
|
|
60
|
+
adapterId: request.adapterId,
|
|
61
|
+
model: null,
|
|
62
|
+
messages: result.messages,
|
|
63
|
+
usage: result.usage,
|
|
64
|
+
stopReason: result.stopReason,
|
|
65
|
+
...(request.metadata ? { metadata: request.metadata } : {}),
|
|
66
|
+
});
|
|
67
|
+
} finally {
|
|
68
|
+
signal?.removeEventListener("abort", abort);
|
|
69
|
+
await controller.stop();
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function abortError(): Error {
|
|
75
|
+
const error = new Error("internal inference aborted");
|
|
76
|
+
error.name = "AbortError";
|
|
77
|
+
return error;
|
|
78
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
InternalInferencePurpose,
|
|
3
|
+
InternalInferenceStrategy,
|
|
4
|
+
} from "../contracts.ts";
|
|
5
|
+
|
|
6
|
+
export class InternalInferenceStrategyRegistry {
|
|
7
|
+
private readonly strategies = new Map<string, InternalInferenceStrategy>();
|
|
8
|
+
|
|
9
|
+
constructor(strategies: readonly InternalInferenceStrategy[] = []) {
|
|
10
|
+
for (const strategy of strategies) this.register(strategy);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
register(strategy: InternalInferenceStrategy): void {
|
|
14
|
+
const key = strategyKey(strategy.purpose, strategy.strategyId, strategy.version);
|
|
15
|
+
if (this.strategies.has(key)) throw new Error(`duplicate internal inference strategy: ${key}`);
|
|
16
|
+
this.strategies.set(key, strategy);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
get(
|
|
20
|
+
purpose: InternalInferencePurpose,
|
|
21
|
+
strategyId: string,
|
|
22
|
+
version: number,
|
|
23
|
+
): InternalInferenceStrategy | undefined {
|
|
24
|
+
return this.strategies.get(strategyKey(purpose, strategyId, version));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
require(
|
|
28
|
+
purpose: InternalInferencePurpose,
|
|
29
|
+
strategyId: string,
|
|
30
|
+
version: number,
|
|
31
|
+
): InternalInferenceStrategy {
|
|
32
|
+
const strategy = this.get(purpose, strategyId, version);
|
|
33
|
+
if (!strategy) {
|
|
34
|
+
throw new Error(`unknown internal inference strategy: ${strategyKey(purpose, strategyId, version)}`);
|
|
35
|
+
}
|
|
36
|
+
return strategy;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function strategyKey(purpose: InternalInferencePurpose, id: string, version: number): string {
|
|
41
|
+
return `${purpose}:${id}@${version}`;
|
|
42
|
+
}
|