@qlairoslabs/acp-client 0.6.0 → 0.7.1
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/CONSUMER_GUIDE.md +618 -291
- package/README.md +25 -0
- package/package.json +1 -1
- package/src/agent-session.ts +2188 -96
- package/src/cli/index.ts +33 -5
- package/src/cli/managed.ts +220 -0
- package/src/command-descriptors.ts +22 -0
- package/src/controller.ts +87 -37
- package/src/index.ts +229 -3
- package/src/metering/engine.ts +9 -1
- package/src/metering/record.ts +2 -1
- package/src/persistence/activity-projection.ts +71 -0
- package/src/persistence/audit-log-reader.ts +506 -0
- package/src/persistence/audit-runtime.ts +162 -0
- package/src/persistence/checkpoint.ts +304 -0
- package/src/persistence/config.ts +538 -0
- package/src/persistence/configuration-state.ts +191 -0
- package/src/persistence/deletion.ts +227 -0
- package/src/persistence/file-registry-store.ts +740 -0
- package/src/persistence/integrity.ts +147 -0
- package/src/persistence/legacy-registry-import.ts +240 -0
- package/src/persistence/managed-checkpoint.ts +81 -0
- package/src/persistence/managed-creation.ts +456 -0
- package/src/persistence/managed-load.ts +172 -0
- package/src/persistence/managed-registry.ts +57 -0
- package/src/persistence/migration.ts +298 -0
- package/src/persistence/paths.ts +172 -0
- package/src/persistence/projection.ts +373 -0
- package/src/persistence/reconfiguration.ts +453 -0
- package/src/persistence/records.ts +873 -0
- package/src/persistence/reducer.ts +498 -0
- package/src/persistence/registry.ts +446 -0
- package/src/persistence/restoration.ts +689 -0
- package/src/persistence/session-log-writer.ts +480 -0
- package/src/persistence/state-runtime.ts +176 -0
- package/src/persistence/transcript-reader.ts +980 -0
- package/src/persistence/transcript-runtime.ts +667 -0
- package/src/persistence/transcript-scanner.ts +385 -0
- package/src/persistence/truncation.ts +276 -0
- package/src/repl/agent-session-commands.ts +74 -1
- package/src/repl/commands.ts +1 -1
- package/src/repl/index.ts +7 -1
- package/src/session-manager.ts +257 -7
- package/src/transcript.ts +3 -3
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { chmod, lstat, mkdir, open, unlink } from "node:fs/promises";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import {
|
|
5
|
+
AgentSession,
|
|
6
|
+
type AgentSessionConfig,
|
|
7
|
+
type ManagedAgentSessionPersistenceSnapshot,
|
|
8
|
+
} from "../agent-session.ts";
|
|
9
|
+
import type {
|
|
10
|
+
AgentSessionPersistenceOptions,
|
|
11
|
+
ManagedSessionPersistenceOptions,
|
|
12
|
+
ResolvedAgentSessionPersistence,
|
|
13
|
+
} from "./config.ts";
|
|
14
|
+
import { resolveSessionLogPaths } from "./paths.ts";
|
|
15
|
+
import {
|
|
16
|
+
AgentSessionStoreConflictError,
|
|
17
|
+
MaintenanceAlreadyCompletedError,
|
|
18
|
+
type AgentSessionRecord,
|
|
19
|
+
type AgentSessionStore,
|
|
20
|
+
type CreationMaintenance,
|
|
21
|
+
} from "./registry.ts";
|
|
22
|
+
import type { InternalSessionHistoryEntry } from "./records.ts";
|
|
23
|
+
import { sha256CanonicalJson } from "./integrity.ts";
|
|
24
|
+
import {
|
|
25
|
+
acquireSessionLogWriterLock,
|
|
26
|
+
type SessionLogWriterLock,
|
|
27
|
+
} from "./session-log-writer.ts";
|
|
28
|
+
import { attachManagedRegistryPublisher } from "./managed-registry.ts";
|
|
29
|
+
import { AuditPersistenceRuntime } from "./audit-runtime.ts";
|
|
30
|
+
|
|
31
|
+
// Retain the former module-level export while the canonical error now applies to every
|
|
32
|
+
// maintenance kind and lives with the shared registry contract.
|
|
33
|
+
export { MaintenanceAlreadyCompletedError } from "./registry.ts";
|
|
34
|
+
|
|
35
|
+
export interface ManagedAgentSessionCreateConfig extends Omit<
|
|
36
|
+
AgentSessionConfig,
|
|
37
|
+
| "agentSessionId"
|
|
38
|
+
| "creationId"
|
|
39
|
+
| "providerSession"
|
|
40
|
+
| "internalSessionId"
|
|
41
|
+
| "sessions"
|
|
42
|
+
| "persistence"
|
|
43
|
+
| "transcriptPath"
|
|
44
|
+
| "transcriptDir"
|
|
45
|
+
| "mode"
|
|
46
|
+
> {
|
|
47
|
+
/** Optional stable identity. Generated when omitted and discoverable through maintenance. */
|
|
48
|
+
readonly agentSessionId?: string;
|
|
49
|
+
/** Optional retry/incarnation identity. Generated when omitted. */
|
|
50
|
+
readonly creationId?: string;
|
|
51
|
+
readonly mode?: "normal";
|
|
52
|
+
readonly persistence?: ManagedSessionPersistenceOptions;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export class ManagedAgentSessionCreationError extends Error {
|
|
56
|
+
constructor(message: string, options?: ErrorOptions) {
|
|
57
|
+
super(message, options);
|
|
58
|
+
this.name = "ManagedAgentSessionCreationError";
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface ManagedCreationContext {
|
|
63
|
+
readonly store: AgentSessionStore;
|
|
64
|
+
readonly persistence: ResolvedAgentSessionPersistence;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** @internal Transaction coordinator used by SessionManager.createAgentSession(). */
|
|
68
|
+
export async function createManagedAgentSession(
|
|
69
|
+
context: ManagedCreationContext,
|
|
70
|
+
config: ManagedAgentSessionCreateConfig,
|
|
71
|
+
): Promise<AgentSession> {
|
|
72
|
+
if (config.mode !== undefined && config.mode !== "normal") {
|
|
73
|
+
throw new ManagedAgentSessionCreationError("managed transcript creation currently requires normal ACP mode");
|
|
74
|
+
}
|
|
75
|
+
const agentSessionId = nonblankOrGenerated(config.agentSessionId, "agentSessionId");
|
|
76
|
+
const creationId = nonblankOrGenerated(config.creationId, "creationId");
|
|
77
|
+
const paths = await resolveSessionLogPaths(context.persistence, agentSessionId);
|
|
78
|
+
const transcriptPath = paths.transcriptPath;
|
|
79
|
+
const requestDigest = sha256CanonicalJson({
|
|
80
|
+
agentSessionId,
|
|
81
|
+
creationId,
|
|
82
|
+
adapterId: config.adapterId,
|
|
83
|
+
mode: "normal",
|
|
84
|
+
cwd: config.cwd ?? null,
|
|
85
|
+
title: config.title ?? null,
|
|
86
|
+
transcript: context.persistence.transcript === false ? null : {
|
|
87
|
+
path: transcriptPath,
|
|
88
|
+
preset: context.persistence.transcript.preset,
|
|
89
|
+
capture: context.persistence.transcript.capture,
|
|
90
|
+
includeTruncationDigests: context.persistence.transcript.includeTruncationDigests,
|
|
91
|
+
},
|
|
92
|
+
sessionConfiguration: context.persistence.sessionConfiguration,
|
|
93
|
+
limits: context.persistence.limits,
|
|
94
|
+
});
|
|
95
|
+
const proposed = creationMaintenance(creationId, requestDigest, transcriptPath, paths.auditLogPath);
|
|
96
|
+
|
|
97
|
+
// Completed retries are answered without touching the artifact or starting a harness.
|
|
98
|
+
if (await context.store.getAgentSessionRecord(agentSessionId)) {
|
|
99
|
+
const result = await context.store.prepareMaintenance(agentSessionId, proposed, {
|
|
100
|
+
expectedRecordRevision: null,
|
|
101
|
+
});
|
|
102
|
+
if (result.status === "already_completed") throw new MaintenanceAlreadyCompletedError(result.receipt);
|
|
103
|
+
throw new AgentSessionStoreConflictError("managed creation requires an unused logical identity");
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
for (const path of [transcriptPath, paths.auditLogPath]) {
|
|
107
|
+
if (!path) continue;
|
|
108
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
109
|
+
await chmod(dirname(path), 0o700).catch(() => undefined);
|
|
110
|
+
}
|
|
111
|
+
const acquired = new Map<string, SessionLogWriterLock>();
|
|
112
|
+
try {
|
|
113
|
+
for (const path of [transcriptPath, paths.auditLogPath]
|
|
114
|
+
.filter((value): value is string => value !== null)
|
|
115
|
+
.sort((left, right) => left.localeCompare(right))) {
|
|
116
|
+
acquired.set(path, await acquireSessionLogWriterLock(path));
|
|
117
|
+
}
|
|
118
|
+
} catch (error) {
|
|
119
|
+
await Promise.all([...acquired.values()].map((lock) => lock.release().catch(() => undefined)));
|
|
120
|
+
throw error;
|
|
121
|
+
}
|
|
122
|
+
const transcriptLock = transcriptPath ? acquired.get(transcriptPath) : undefined;
|
|
123
|
+
const auditLogLock = paths.auditLogPath ? acquired.get(paths.auditLogPath) : undefined;
|
|
124
|
+
let lockTransferred = false;
|
|
125
|
+
let session: AgentSession | null = null;
|
|
126
|
+
try {
|
|
127
|
+
const priorMaintenance = await context.store.getMaintenance(agentSessionId);
|
|
128
|
+
if (!priorMaintenance) {
|
|
129
|
+
if (transcriptPath) await requireUninitializedDestination(transcriptPath);
|
|
130
|
+
if (paths.auditLogPath) await requireUninitializedDestination(paths.auditLogPath);
|
|
131
|
+
}
|
|
132
|
+
const prepared = await context.store.prepareMaintenance(agentSessionId, proposed, {
|
|
133
|
+
expectedRecordRevision: null,
|
|
134
|
+
});
|
|
135
|
+
if (prepared.status === "already_completed") {
|
|
136
|
+
throw new MaintenanceAlreadyCompletedError(prepared.receipt);
|
|
137
|
+
}
|
|
138
|
+
if (prepared.maintenance.kind !== "creation") {
|
|
139
|
+
throw new ManagedAgentSessionCreationError("prepared maintenance is not creation");
|
|
140
|
+
}
|
|
141
|
+
let active = prepared.maintenance;
|
|
142
|
+
if (active.details.stagedRecord) {
|
|
143
|
+
await context.store.finalizeMaintenance(
|
|
144
|
+
agentSessionId,
|
|
145
|
+
creationId,
|
|
146
|
+
creationId,
|
|
147
|
+
requestDigest,
|
|
148
|
+
{ save: active.details.stagedRecord },
|
|
149
|
+
);
|
|
150
|
+
const stored = active.details.stagedRecord;
|
|
151
|
+
const audit = stored.auditLog
|
|
152
|
+
? await AuditPersistenceRuntime.resume({
|
|
153
|
+
path: stored.auditLog.path,
|
|
154
|
+
agentSessionId,
|
|
155
|
+
auditLogId: stored.auditLog.auditLogId,
|
|
156
|
+
generation: stored.auditLog.generation,
|
|
157
|
+
writerLock: auditLogLock,
|
|
158
|
+
})
|
|
159
|
+
: undefined;
|
|
160
|
+
lockTransferred = true;
|
|
161
|
+
const opened = active.details.stagedRecord.transcript
|
|
162
|
+
? await AgentSession.openManaged({
|
|
163
|
+
...runtimeConfig(config),
|
|
164
|
+
agentSessionId,
|
|
165
|
+
persistence: directPersistence(context.persistence, transcriptPath),
|
|
166
|
+
checkpoint: active.details.stagedRecord.checkpoint,
|
|
167
|
+
}, transcriptLock, audit)
|
|
168
|
+
: await AgentSession.openManagedRegistry({
|
|
169
|
+
...runtimeConfig(config),
|
|
170
|
+
agentSessionId,
|
|
171
|
+
persistence: directPersistence(context.persistence, null),
|
|
172
|
+
checkpoint: active.details.stagedRecord.checkpoint,
|
|
173
|
+
}, active.details.stagedRecord.internalSessionHistory, audit);
|
|
174
|
+
attachManagedRegistryPublisher(opened.session, context.store);
|
|
175
|
+
return opened.session;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (prepared.status === "already_prepared") {
|
|
179
|
+
if (transcriptPath) {
|
|
180
|
+
await removeOwnedCreationArtifact(
|
|
181
|
+
transcriptPath, agentSessionId, creationId, requestDigest,
|
|
182
|
+
context.persistence.limits.maxRecordBytes, "transcript",
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
if (paths.auditLogPath) {
|
|
186
|
+
await removeOwnedCreationArtifact(
|
|
187
|
+
paths.auditLogPath, agentSessionId, creationId, requestDigest,
|
|
188
|
+
context.persistence.limits.maxRecordBytes, "audit",
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
const stagedContinuation = active.details.stagedContinuation;
|
|
193
|
+
lockTransferred = true;
|
|
194
|
+
session = await AgentSession.createManaged({
|
|
195
|
+
...runtimeConfig(config),
|
|
196
|
+
agentSessionId,
|
|
197
|
+
creationId,
|
|
198
|
+
mode: "normal",
|
|
199
|
+
providerSession: stagedContinuation?.internalSessionId
|
|
200
|
+
? { kind: "load", internalSessionId: stagedContinuation.internalSessionId, onFailure: "error" }
|
|
201
|
+
: { kind: "new" },
|
|
202
|
+
persistence: directPersistence(context.persistence, transcriptPath),
|
|
203
|
+
}, {
|
|
204
|
+
requestDigest,
|
|
205
|
+
transcriptLock,
|
|
206
|
+
auditLogLock,
|
|
207
|
+
stageContinuation: async (state) => {
|
|
208
|
+
const existing = active.details.stagedContinuation;
|
|
209
|
+
if (existing) {
|
|
210
|
+
if (existing.adapterId !== state.adapterId
|
|
211
|
+
|| existing.mode !== state.mode
|
|
212
|
+
|| existing.internalSessionId !== state.internalSessionId) {
|
|
213
|
+
throw new ManagedAgentSessionCreationError(
|
|
214
|
+
"loaded provider thread disagrees with staged continuation identity",
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
return existing;
|
|
218
|
+
}
|
|
219
|
+
const update: CreationMaintenance = {
|
|
220
|
+
...active,
|
|
221
|
+
details: { ...active.details, stagedContinuation: state },
|
|
222
|
+
};
|
|
223
|
+
await context.store.updateMaintenance(agentSessionId, creationId, creationId, update);
|
|
224
|
+
active = update;
|
|
225
|
+
return state;
|
|
226
|
+
},
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
const snapshot = session.getManagedPersistenceSnapshot();
|
|
230
|
+
const record = initialRecord(
|
|
231
|
+
config,
|
|
232
|
+
context.persistence,
|
|
233
|
+
active,
|
|
234
|
+
snapshot,
|
|
235
|
+
);
|
|
236
|
+
const staged: CreationMaintenance = {
|
|
237
|
+
...active,
|
|
238
|
+
details: { ...active.details, stagedRecord: record },
|
|
239
|
+
};
|
|
240
|
+
await context.store.updateMaintenance(agentSessionId, creationId, creationId, staged);
|
|
241
|
+
await context.store.finalizeMaintenance(
|
|
242
|
+
agentSessionId,
|
|
243
|
+
creationId,
|
|
244
|
+
creationId,
|
|
245
|
+
requestDigest,
|
|
246
|
+
{ save: record },
|
|
247
|
+
);
|
|
248
|
+
attachManagedRegistryPublisher(session, context.store);
|
|
249
|
+
return session;
|
|
250
|
+
} catch (error) {
|
|
251
|
+
await session?.stop().catch(() => undefined);
|
|
252
|
+
throw error;
|
|
253
|
+
} finally {
|
|
254
|
+
if (!lockTransferred) {
|
|
255
|
+
await Promise.all([...acquired.values()].map((lock) => lock.release().catch(() => undefined)));
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function runtimeConfig(config: ManagedAgentSessionCreateConfig): Omit<
|
|
261
|
+
AgentSessionConfig,
|
|
262
|
+
"agentSessionId" | "creationId" | "providerSession" | "persistence" | "mode"
|
|
263
|
+
> {
|
|
264
|
+
const {
|
|
265
|
+
agentSessionId: _agentSessionId,
|
|
266
|
+
creationId: _creationId,
|
|
267
|
+
persistence: _persistence,
|
|
268
|
+
mode: _mode,
|
|
269
|
+
...runtime
|
|
270
|
+
} = config;
|
|
271
|
+
return runtime;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function directPersistence(
|
|
275
|
+
persistence: ResolvedAgentSessionPersistence,
|
|
276
|
+
transcriptPath: string | null,
|
|
277
|
+
): AgentSessionPersistenceOptions {
|
|
278
|
+
if (persistence.transcript !== false && !transcriptPath) {
|
|
279
|
+
throw new ManagedAgentSessionCreationError("enabled transcript has no resolved path");
|
|
280
|
+
}
|
|
281
|
+
return {
|
|
282
|
+
root: persistence.root,
|
|
283
|
+
transcript: persistence.transcript === false ? false : {
|
|
284
|
+
path: transcriptPath!,
|
|
285
|
+
preset: persistence.transcript.preset,
|
|
286
|
+
capture: persistence.transcript.capture,
|
|
287
|
+
includeTruncationDigests: persistence.transcript.includeTruncationDigests,
|
|
288
|
+
},
|
|
289
|
+
auditLog: persistence.auditLog === false ? false : {
|
|
290
|
+
path: persistence.auditLog.path,
|
|
291
|
+
capture: persistence.auditLog.capture,
|
|
292
|
+
includeTruncationDigests: persistence.auditLog.includeTruncationDigests,
|
|
293
|
+
},
|
|
294
|
+
sessionConfiguration: persistence.sessionConfiguration,
|
|
295
|
+
limits: persistence.limits,
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function creationMaintenance(
|
|
300
|
+
creationId: string,
|
|
301
|
+
requestDigest: string,
|
|
302
|
+
transcriptPath: string | null,
|
|
303
|
+
auditLogPath: string | null,
|
|
304
|
+
): CreationMaintenance {
|
|
305
|
+
return {
|
|
306
|
+
kind: "creation",
|
|
307
|
+
incarnationId: creationId,
|
|
308
|
+
baseRecordRevision: null,
|
|
309
|
+
operationId: creationId,
|
|
310
|
+
requestDigest,
|
|
311
|
+
status: "prepared",
|
|
312
|
+
startedAt: new Date().toISOString(),
|
|
313
|
+
details: { transcriptPath, auditLogPath },
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function initialRecord(
|
|
318
|
+
config: ManagedAgentSessionCreateConfig,
|
|
319
|
+
persistence: ResolvedAgentSessionPersistence,
|
|
320
|
+
maintenance: CreationMaintenance,
|
|
321
|
+
snapshot: ManagedAgentSessionPersistenceSnapshot,
|
|
322
|
+
): AgentSessionRecord {
|
|
323
|
+
const { checkpoint, internalSessionHistory: history } = snapshot;
|
|
324
|
+
if (persistence.transcript !== false && !checkpoint.transcript) {
|
|
325
|
+
throw new ManagedAgentSessionCreationError("enabled transcript has no checkpoint identity");
|
|
326
|
+
}
|
|
327
|
+
return {
|
|
328
|
+
agentSessionId: checkpoint.agentSessionId,
|
|
329
|
+
incarnationId: checkpoint.incarnationId,
|
|
330
|
+
recordRevision: 1,
|
|
331
|
+
checkpoint,
|
|
332
|
+
adapterId: checkpoint.adapterId,
|
|
333
|
+
mode: checkpoint.mode,
|
|
334
|
+
internalSessionId: checkpoint.internalSessionId,
|
|
335
|
+
internalSessionActivatedAt: checkpoint.internalSessionActivatedAt,
|
|
336
|
+
internalSessionHistory: history,
|
|
337
|
+
...(config.cwd === undefined ? {} : { cwd: config.cwd }),
|
|
338
|
+
...(config.title === undefined ? {} : { title: config.title }),
|
|
339
|
+
model: checkpoint.model,
|
|
340
|
+
sessionConfiguration: checkpoint.sessionConfiguration,
|
|
341
|
+
sessionConfigurationPersistence: persistence.sessionConfiguration,
|
|
342
|
+
protocol: checkpoint.protocol,
|
|
343
|
+
transcript: persistence.transcript === false ? null : {
|
|
344
|
+
path: checkpoint.transcript!.path,
|
|
345
|
+
transcriptId: checkpoint.transcript!.transcriptId,
|
|
346
|
+
generation: checkpoint.transcript!.generation,
|
|
347
|
+
preset: persistence.transcript.preset,
|
|
348
|
+
effectivePolicy: persistence.transcript.capture,
|
|
349
|
+
effectiveLimits: persistence.limits,
|
|
350
|
+
includeTruncationDigests: persistence.transcript.includeTruncationDigests,
|
|
351
|
+
},
|
|
352
|
+
auditLog: snapshotAuditMetadata(persistence, snapshot),
|
|
353
|
+
createdAt: maintenance.startedAt,
|
|
354
|
+
updatedAt: checkpoint.updatedAt < maintenance.startedAt ? maintenance.startedAt : checkpoint.updatedAt,
|
|
355
|
+
lastOpenedAt: checkpoint.updatedAt < maintenance.startedAt ? maintenance.startedAt : checkpoint.updatedAt,
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
async function requireUninitializedDestination(path: string): Promise<void> {
|
|
360
|
+
try {
|
|
361
|
+
const info = await lstat(path);
|
|
362
|
+
if (!info.isFile() || info.isSymbolicLink() || info.size !== 0) {
|
|
363
|
+
throw new ManagedAgentSessionCreationError(`managed transcript destination is already initialized: ${path}`);
|
|
364
|
+
}
|
|
365
|
+
} catch (error) {
|
|
366
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
|
|
367
|
+
throw error;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
async function removeOwnedCreationArtifact(
|
|
372
|
+
path: string,
|
|
373
|
+
agentSessionId: string,
|
|
374
|
+
creationId: string,
|
|
375
|
+
requestDigest: string,
|
|
376
|
+
maxRecordBytes: number,
|
|
377
|
+
kind: "transcript" | "audit",
|
|
378
|
+
): Promise<void> {
|
|
379
|
+
let info;
|
|
380
|
+
try {
|
|
381
|
+
info = await lstat(path);
|
|
382
|
+
} catch (error) {
|
|
383
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
|
|
384
|
+
throw error;
|
|
385
|
+
}
|
|
386
|
+
if (!info.isFile() || info.isSymbolicLink()) {
|
|
387
|
+
throw new ManagedAgentSessionCreationError("prepared transcript artifact is not a regular file");
|
|
388
|
+
}
|
|
389
|
+
if (info.size === 0) return;
|
|
390
|
+
const first = await firstJsonLine(path, maxRecordBytes);
|
|
391
|
+
if (!isRecord(first)
|
|
392
|
+
|| first.v !== (kind === "transcript" ? 2 : 1)
|
|
393
|
+
|| first.t !== "header"
|
|
394
|
+
|| first.agentSessionId !== agentSessionId
|
|
395
|
+
|| !isRecord(first.installation)
|
|
396
|
+
|| first.installation.kind !== "creation"
|
|
397
|
+
|| first.installation.operationId !== creationId
|
|
398
|
+
|| first.installation.requestDigest !== requestDigest) {
|
|
399
|
+
throw new ManagedAgentSessionCreationError(
|
|
400
|
+
"prepared transcript artifact does not belong to this creation transaction",
|
|
401
|
+
);
|
|
402
|
+
}
|
|
403
|
+
await unlink(path);
|
|
404
|
+
const parent = await open(dirname(path), "r");
|
|
405
|
+
try {
|
|
406
|
+
await parent.sync();
|
|
407
|
+
} finally {
|
|
408
|
+
await parent.close();
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
function snapshotAuditMetadata(
|
|
413
|
+
persistence: ResolvedAgentSessionPersistence,
|
|
414
|
+
snapshot: ManagedAgentSessionPersistenceSnapshot,
|
|
415
|
+
): AgentSessionRecord["auditLog"] {
|
|
416
|
+
if (persistence.auditLog === false) return null;
|
|
417
|
+
const identity = snapshot?.auditLog;
|
|
418
|
+
if (!identity) throw new ManagedAgentSessionCreationError("enabled audit log has no installed identity");
|
|
419
|
+
return {
|
|
420
|
+
path: identity.path,
|
|
421
|
+
auditLogId: identity.auditLogId,
|
|
422
|
+
generation: identity.generation,
|
|
423
|
+
effectivePolicy: persistence.auditLog.capture,
|
|
424
|
+
effectiveLimits: persistence.limits,
|
|
425
|
+
includeTruncationDigests: persistence.auditLog.includeTruncationDigests,
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
async function firstJsonLine(path: string, maxBytes: number): Promise<unknown> {
|
|
430
|
+
const handle = await open(path, "r");
|
|
431
|
+
try {
|
|
432
|
+
const capacity = Math.min(maxBytes + 1, 16_777_217);
|
|
433
|
+
const buffer = Buffer.alloc(capacity);
|
|
434
|
+
const { bytesRead } = await handle.read(buffer, 0, capacity, 0);
|
|
435
|
+
const newline = buffer.subarray(0, bytesRead).indexOf(0x0a);
|
|
436
|
+
if (newline < 0 || newline > maxBytes) {
|
|
437
|
+
throw new ManagedAgentSessionCreationError("prepared transcript header exceeds its record limit");
|
|
438
|
+
}
|
|
439
|
+
return JSON.parse(buffer.subarray(0, newline).toString("utf8"));
|
|
440
|
+
} catch (error) {
|
|
441
|
+
if (error instanceof ManagedAgentSessionCreationError) throw error;
|
|
442
|
+
throw new ManagedAgentSessionCreationError("prepared transcript header is malformed", { cause: error });
|
|
443
|
+
} finally {
|
|
444
|
+
await handle.close();
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function nonblankOrGenerated(value: string | undefined, label: string): string {
|
|
449
|
+
if (value === undefined) return randomUUID();
|
|
450
|
+
if (!value.trim()) throw new ManagedAgentSessionCreationError(`${label} cannot be blank`);
|
|
451
|
+
return value;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
455
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
456
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AdapterMismatchError,
|
|
3
|
+
AgentSession,
|
|
4
|
+
type AgentSessionOpenConfig,
|
|
5
|
+
type AgentSessionOpenResult,
|
|
6
|
+
} from "../agent-session.ts";
|
|
7
|
+
import type { AgentSessionPersistenceOptions } from "./config.ts";
|
|
8
|
+
import {
|
|
9
|
+
AgentSessionStoreConflictError,
|
|
10
|
+
SessionMaintenanceInProgressError,
|
|
11
|
+
type AgentSessionRecord,
|
|
12
|
+
type AgentSessionStore,
|
|
13
|
+
} from "./registry.ts";
|
|
14
|
+
import {
|
|
15
|
+
attachManagedRegistryPublisher,
|
|
16
|
+
projectManagedAgentSessionRecord,
|
|
17
|
+
} from "./managed-registry.ts";
|
|
18
|
+
import { AuditPersistenceRuntime } from "./audit-runtime.ts";
|
|
19
|
+
|
|
20
|
+
export interface ManagedAgentSessionLoadConfig extends Omit<
|
|
21
|
+
AgentSessionOpenConfig,
|
|
22
|
+
"agentSessionId" | "persistence" | "checkpoint"
|
|
23
|
+
> {}
|
|
24
|
+
|
|
25
|
+
export class ManagedAgentSessionNotFoundError extends Error {
|
|
26
|
+
constructor(readonly agentSessionId: string) {
|
|
27
|
+
super(`managed agent session ${agentSessionId} was not found`);
|
|
28
|
+
this.name = "ManagedAgentSessionNotFoundError";
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export class ManagedAgentSessionDeletedError extends Error {
|
|
33
|
+
constructor(readonly agentSessionId: string) {
|
|
34
|
+
super(`managed agent session ${agentSessionId} is deleted; restore it explicitly before loading`);
|
|
35
|
+
this.name = "ManagedAgentSessionDeletedError";
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export class ManagedAgentSessionAuthorityConflictError extends AgentSessionStoreConflictError {
|
|
40
|
+
constructor(message: string) {
|
|
41
|
+
super(message);
|
|
42
|
+
this.name = "ManagedAgentSessionAuthorityConflictError";
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** @internal Open one cataloged transcript authority and reconcile its registry projection. */
|
|
47
|
+
export async function loadManagedAgentSession(
|
|
48
|
+
store: AgentSessionStore,
|
|
49
|
+
agentSessionId: string,
|
|
50
|
+
config: ManagedAgentSessionLoadConfig,
|
|
51
|
+
): Promise<AgentSessionOpenResult> {
|
|
52
|
+
const [record, maintenance] = await Promise.all([
|
|
53
|
+
store.getAgentSessionRecord(agentSessionId),
|
|
54
|
+
store.getMaintenance(agentSessionId),
|
|
55
|
+
]);
|
|
56
|
+
if (!record) throw new ManagedAgentSessionNotFoundError(agentSessionId);
|
|
57
|
+
if (maintenance) throw new SessionMaintenanceInProgressError(agentSessionId);
|
|
58
|
+
if (record.deletion) throw new ManagedAgentSessionDeletedError(agentSessionId);
|
|
59
|
+
if (record.mode !== "normal") {
|
|
60
|
+
throw new ManagedAgentSessionAuthorityConflictError("managed loading currently requires normal ACP mode");
|
|
61
|
+
}
|
|
62
|
+
if (record.adapterId !== config.adapterId && !hasReconstructionStrategy(config)) {
|
|
63
|
+
throw new AdapterMismatchError(record.adapterId, config.adapterId);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const audit = record.auditLog
|
|
67
|
+
? await AuditPersistenceRuntime.resume({
|
|
68
|
+
path: record.auditLog.path,
|
|
69
|
+
agentSessionId,
|
|
70
|
+
auditLogId: record.auditLog.auditLogId,
|
|
71
|
+
generation: record.auditLog.generation,
|
|
72
|
+
})
|
|
73
|
+
: undefined;
|
|
74
|
+
let opened: AgentSessionOpenResult;
|
|
75
|
+
try {
|
|
76
|
+
opened = record.transcript
|
|
77
|
+
? await AgentSession.openManaged({
|
|
78
|
+
...config,
|
|
79
|
+
agentSessionId,
|
|
80
|
+
persistence: persistenceFromManagedRecord(record),
|
|
81
|
+
}, undefined, audit)
|
|
82
|
+
: await AgentSession.openManagedRegistry({
|
|
83
|
+
...config,
|
|
84
|
+
agentSessionId,
|
|
85
|
+
checkpoint: record.checkpoint,
|
|
86
|
+
persistence: {
|
|
87
|
+
transcript: false,
|
|
88
|
+
auditLog: false,
|
|
89
|
+
sessionConfiguration: record.sessionConfigurationPersistence ?? { values: "typed" },
|
|
90
|
+
},
|
|
91
|
+
}, record.internalSessionHistory, audit);
|
|
92
|
+
} catch (error) {
|
|
93
|
+
await audit?.close().catch(() => undefined);
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
const snapshot = opened.session.getManagedPersistenceSnapshot();
|
|
98
|
+
assertCompatibleAuthority(record, snapshot.checkpoint);
|
|
99
|
+
const current = await store.getAgentSessionRecord(agentSessionId);
|
|
100
|
+
if (!current || current.incarnationId !== record.incarnationId) {
|
|
101
|
+
throw new ManagedAgentSessionAuthorityConflictError(
|
|
102
|
+
"managed registry identity changed while the transcript was opening",
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
if (await store.getMaintenance(agentSessionId)) {
|
|
106
|
+
throw new SessionMaintenanceInProgressError(agentSessionId);
|
|
107
|
+
}
|
|
108
|
+
assertCompatibleAuthority(current, snapshot.checkpoint);
|
|
109
|
+
const openedAt = new Date().toISOString();
|
|
110
|
+
const next = projectManagedAgentSessionRecord(
|
|
111
|
+
current,
|
|
112
|
+
snapshot.checkpoint,
|
|
113
|
+
snapshot.internalSessionHistory,
|
|
114
|
+
{ lastOpenedAt: openedAt },
|
|
115
|
+
);
|
|
116
|
+
await store.saveAgentSessionRecord(next, {
|
|
117
|
+
expectedRecordRevision: current.recordRevision,
|
|
118
|
+
expectedIncarnationId: current.incarnationId,
|
|
119
|
+
});
|
|
120
|
+
attachManagedRegistryPublisher(opened.session, store);
|
|
121
|
+
return opened;
|
|
122
|
+
} catch (error) {
|
|
123
|
+
await opened.session.stop().catch(() => undefined);
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function persistenceFromManagedRecord(record: AgentSessionRecord): AgentSessionPersistenceOptions {
|
|
129
|
+
if (!record.transcript) throw new ManagedAgentSessionAuthorityConflictError("transcript is unavailable");
|
|
130
|
+
return {
|
|
131
|
+
transcript: {
|
|
132
|
+
path: record.transcript.path,
|
|
133
|
+
preset: record.transcript.preset,
|
|
134
|
+
capture: record.transcript.effectivePolicy,
|
|
135
|
+
includeTruncationDigests: record.transcript.includeTruncationDigests,
|
|
136
|
+
},
|
|
137
|
+
auditLog: record.auditLog ? {
|
|
138
|
+
path: record.auditLog.path,
|
|
139
|
+
capture: record.auditLog.effectivePolicy,
|
|
140
|
+
includeTruncationDigests: record.auditLog.includeTruncationDigests,
|
|
141
|
+
} : false,
|
|
142
|
+
sessionConfiguration: record.sessionConfigurationPersistence ?? { values: "typed" },
|
|
143
|
+
limits: record.transcript.effectiveLimits,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function assertCompatibleAuthority(
|
|
148
|
+
registry: AgentSessionRecord,
|
|
149
|
+
transcript: AgentSessionRecord["checkpoint"],
|
|
150
|
+
): void {
|
|
151
|
+
if (registry.agentSessionId !== transcript.agentSessionId
|
|
152
|
+
|| registry.incarnationId !== transcript.incarnationId) {
|
|
153
|
+
throw new ManagedAgentSessionAuthorityConflictError(
|
|
154
|
+
"registry and transcript identify different logical session incarnations",
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
if (registry.checkpoint.stateRevision > transcript.stateRevision) {
|
|
158
|
+
throw new ManagedAgentSessionAuthorityConflictError(
|
|
159
|
+
"registry checkpoint is newer than transcript authority and cannot be reconciled",
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
if (registry.checkpoint.stateRevision === transcript.stateRevision
|
|
163
|
+
&& registry.checkpoint.digest !== transcript.digest) {
|
|
164
|
+
throw new ManagedAgentSessionAuthorityConflictError(
|
|
165
|
+
"registry and transcript checkpoints disagree at the same revision",
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function hasReconstructionStrategy(config: ManagedAgentSessionLoadConfig): boolean {
|
|
171
|
+
return config.continuation?.strategies?.some((strategy) => strategy.kind !== "load_internal_session") === true;
|
|
172
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { AgentSession } from "../agent-session.ts";
|
|
2
|
+
import type { AgentSessionCheckpoint } from "./checkpoint.ts";
|
|
3
|
+
import type { InternalSessionHistoryEntry } from "./records.ts";
|
|
4
|
+
import {
|
|
5
|
+
AgentSessionStoreConflictError,
|
|
6
|
+
type AgentSessionRecord,
|
|
7
|
+
type AgentSessionStore,
|
|
8
|
+
} from "./registry.ts";
|
|
9
|
+
|
|
10
|
+
/** Materialize one authoritative checkpoint/history pair over an existing registry row. */
|
|
11
|
+
export function projectManagedAgentSessionRecord(
|
|
12
|
+
current: AgentSessionRecord,
|
|
13
|
+
checkpoint: AgentSessionCheckpoint,
|
|
14
|
+
history: readonly InternalSessionHistoryEntry[],
|
|
15
|
+
options: { readonly lastOpenedAt?: string } = {},
|
|
16
|
+
): AgentSessionRecord {
|
|
17
|
+
if (current.agentSessionId !== checkpoint.agentSessionId
|
|
18
|
+
|| current.incarnationId !== checkpoint.incarnationId) {
|
|
19
|
+
throw new AgentSessionStoreConflictError("managed registry projection identity mismatch");
|
|
20
|
+
}
|
|
21
|
+
const updatedAt = checkpoint.updatedAt < current.updatedAt ? current.updatedAt : checkpoint.updatedAt;
|
|
22
|
+
return {
|
|
23
|
+
...current,
|
|
24
|
+
recordRevision: current.recordRevision + 1,
|
|
25
|
+
checkpoint,
|
|
26
|
+
adapterId: checkpoint.adapterId,
|
|
27
|
+
mode: checkpoint.mode,
|
|
28
|
+
internalSessionId: checkpoint.internalSessionId,
|
|
29
|
+
internalSessionActivatedAt: checkpoint.internalSessionActivatedAt,
|
|
30
|
+
internalSessionHistory: history,
|
|
31
|
+
model: checkpoint.model,
|
|
32
|
+
sessionConfiguration: checkpoint.sessionConfiguration,
|
|
33
|
+
protocol: checkpoint.protocol,
|
|
34
|
+
updatedAt,
|
|
35
|
+
...(options.lastOpenedAt === undefined
|
|
36
|
+
? {}
|
|
37
|
+
: { lastOpenedAt: options.lastOpenedAt < updatedAt ? updatedAt : options.lastOpenedAt }),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Attach ongoing transcript checkpoint publication to the strict managed store. */
|
|
42
|
+
export function attachManagedRegistryPublisher(
|
|
43
|
+
session: AgentSession,
|
|
44
|
+
store: AgentSessionStore,
|
|
45
|
+
): void {
|
|
46
|
+
session.attachManagedCheckpointPublisher(async (checkpoint, history) => {
|
|
47
|
+
const current = await store.getAgentSessionRecord(checkpoint.agentSessionId);
|
|
48
|
+
if (!current || current.incarnationId !== checkpoint.incarnationId) {
|
|
49
|
+
throw new AgentSessionStoreConflictError("managed registry projection identity disappeared");
|
|
50
|
+
}
|
|
51
|
+
const next = projectManagedAgentSessionRecord(current, checkpoint, history);
|
|
52
|
+
await store.saveAgentSessionRecord(next, {
|
|
53
|
+
expectedRecordRevision: current.recordRevision,
|
|
54
|
+
expectedIncarnationId: current.incarnationId,
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
}
|