@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,298 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { chmod, lstat, open } from "node:fs/promises";
|
|
3
|
+
import { isAbsolute } from "node:path";
|
|
4
|
+
import {
|
|
5
|
+
resolveDirectPersistence,
|
|
6
|
+
type PersistenceLimits,
|
|
7
|
+
type TranscriptConfig,
|
|
8
|
+
} from "./config.ts";
|
|
9
|
+
import { createAgentSessionCheckpoint, type AgentSessionCheckpoint } from "./checkpoint.ts";
|
|
10
|
+
import { canonicalizeJson } from "./integrity.ts";
|
|
11
|
+
import {
|
|
12
|
+
validateTranscriptRecord,
|
|
13
|
+
type TranscriptCheckpointRecord,
|
|
14
|
+
type TranscriptHeaderRecord,
|
|
15
|
+
} from "./records.ts";
|
|
16
|
+
import { EMPTY_HISTORY_DIGEST } from "./reducer.ts";
|
|
17
|
+
import type { StagedContinuationState } from "./registry.ts";
|
|
18
|
+
import { withSessionLogWriterLock } from "./session-log-writer.ts";
|
|
19
|
+
import { SESSION_LOG_READER_INTERNALS as IO } from "./transcript-reader.ts";
|
|
20
|
+
|
|
21
|
+
export interface MigrateLegacyTranscriptOptions {
|
|
22
|
+
readonly path: string;
|
|
23
|
+
readonly agentSessionId: string;
|
|
24
|
+
readonly continuation: StagedContinuationState;
|
|
25
|
+
readonly transcript?: Omit<TranscriptConfig, "path">;
|
|
26
|
+
readonly limits?: Partial<PersistenceLimits>;
|
|
27
|
+
readonly transcriptId?: string;
|
|
28
|
+
readonly incarnationId?: string;
|
|
29
|
+
/** Test/embedding clock; evaluated only when a new upgrade header is required. */
|
|
30
|
+
readonly now?: () => Date;
|
|
31
|
+
readonly lockTimeoutMs?: number;
|
|
32
|
+
readonly lockRetryMs?: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface LegacyTranscriptMigrationResult {
|
|
36
|
+
readonly status: "migrated" | "resumed" | "already_migrated";
|
|
37
|
+
readonly header: TranscriptHeaderRecord;
|
|
38
|
+
readonly checkpoint: AgentSessionCheckpoint;
|
|
39
|
+
readonly legacyBoundaryOffset: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export class LegacyTranscriptMigrationError extends Error {
|
|
43
|
+
constructor(message: string, options?: ErrorOptions) {
|
|
44
|
+
super(message, options);
|
|
45
|
+
this.name = "LegacyTranscriptMigrationError";
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Establish a v2 continuation boundary after a legacy v1 transcript.
|
|
51
|
+
*
|
|
52
|
+
* Legacy lines remain presentation-only. The supplied continuation is complete authority;
|
|
53
|
+
* no adapter, provider identity, model, protocol, or configuration is inferred from v1.
|
|
54
|
+
*/
|
|
55
|
+
export async function migrateLegacyTranscript(
|
|
56
|
+
options: MigrateLegacyTranscriptOptions,
|
|
57
|
+
): Promise<LegacyTranscriptMigrationResult> {
|
|
58
|
+
validateOptions(options);
|
|
59
|
+
return withSessionLogWriterLock(options.path, async () => {
|
|
60
|
+
try {
|
|
61
|
+
const stat = await lstat(options.path);
|
|
62
|
+
if (!stat.isFile() || stat.isSymbolicLink()) {
|
|
63
|
+
throw new LegacyTranscriptMigrationError("legacy transcript must be a regular non-symbolic-link file");
|
|
64
|
+
}
|
|
65
|
+
const handle = await open(options.path, "r+");
|
|
66
|
+
try {
|
|
67
|
+
const scan = await scanMigrationFile(handle, stat.size);
|
|
68
|
+
if (scan.header && scan.checkpointRecord) {
|
|
69
|
+
assertExistingMatches(scan.header, scan.checkpointRecord, options);
|
|
70
|
+
return freezeResult("already_migrated", scan.header, scan.checkpointRecord.checkpoint);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const header = scan.header ?? createUpgradeHeader(options, scan.legacyBoundaryOffset);
|
|
74
|
+
if (scan.header) assertHeaderRequestMatches(scan.header, options);
|
|
75
|
+
const checkpoint = createMigrationCheckpoint(
|
|
76
|
+
options,
|
|
77
|
+
header,
|
|
78
|
+
scan.checkpointRecord?.checkpoint.incarnationId ?? options.incarnationId ?? randomUUID(),
|
|
79
|
+
);
|
|
80
|
+
const record = checkpointRecord(header, checkpoint);
|
|
81
|
+
|
|
82
|
+
if (stat.size !== scan.completeOffset) await handle.truncate(scan.completeOffset);
|
|
83
|
+
let position = scan.completeOffset;
|
|
84
|
+
if (!scan.header) {
|
|
85
|
+
const headerLine = Buffer.from(`${JSON.stringify(header)}\n`, "utf8");
|
|
86
|
+
await handle.write(headerLine, 0, headerLine.byteLength, position);
|
|
87
|
+
position += headerLine.byteLength;
|
|
88
|
+
await handle.sync();
|
|
89
|
+
}
|
|
90
|
+
const checkpointLine = Buffer.from(`${JSON.stringify(record)}\n`, "utf8");
|
|
91
|
+
await handle.write(checkpointLine, 0, checkpointLine.byteLength, position);
|
|
92
|
+
await handle.sync();
|
|
93
|
+
await chmod(options.path, 0o600).catch(() => undefined);
|
|
94
|
+
return freezeResult(scan.header ? "resumed" : "migrated", header, checkpoint);
|
|
95
|
+
} finally {
|
|
96
|
+
await handle.close().catch(() => undefined);
|
|
97
|
+
}
|
|
98
|
+
} catch (error) {
|
|
99
|
+
if (error instanceof LegacyTranscriptMigrationError) throw error;
|
|
100
|
+
throw new LegacyTranscriptMigrationError("legacy transcript migration failed", { cause: error });
|
|
101
|
+
}
|
|
102
|
+
}, options);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
interface MigrationScan {
|
|
106
|
+
readonly legacyBoundaryOffset: number;
|
|
107
|
+
readonly completeOffset: number;
|
|
108
|
+
readonly header: TranscriptHeaderRecord | null;
|
|
109
|
+
readonly checkpointRecord: TranscriptCheckpointRecord | null;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function scanMigrationFile(handle: Awaited<ReturnType<typeof open>>, size: number): Promise<MigrationScan> {
|
|
113
|
+
if (size === 0) throw new LegacyTranscriptMigrationError("cannot migrate an empty transcript");
|
|
114
|
+
const completeOffset = await IO.lastCompleteOffset(handle, size);
|
|
115
|
+
let header: TranscriptHeaderRecord | null = null;
|
|
116
|
+
let checkpointRecord: TranscriptCheckpointRecord | null = null;
|
|
117
|
+
let legacyBoundaryOffset = completeOffset;
|
|
118
|
+
for await (const physical of IO.forwardLines(handle, 0, completeOffset, IO.hardMaxRecordBytes)) {
|
|
119
|
+
let value: unknown;
|
|
120
|
+
try {
|
|
121
|
+
value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(physical.bytes));
|
|
122
|
+
} catch {
|
|
123
|
+
if (header) throw new LegacyTranscriptMigrationError("malformed complete record after v2 upgrade boundary");
|
|
124
|
+
continue; // Historical v1 behavior deliberately skips malformed complete lines.
|
|
125
|
+
}
|
|
126
|
+
if (!isRecord(value) || value.v !== 2) {
|
|
127
|
+
if (header) throw new LegacyTranscriptMigrationError("legacy record appears after v2 upgrade boundary");
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
if (!header) {
|
|
131
|
+
try {
|
|
132
|
+
validateTranscriptRecord(value);
|
|
133
|
+
} catch (error) {
|
|
134
|
+
throw new LegacyTranscriptMigrationError("invalid v2 upgrade header in legacy transcript", { cause: error });
|
|
135
|
+
}
|
|
136
|
+
if (value.t !== "header" || value.event !== "upgraded") {
|
|
137
|
+
throw new LegacyTranscriptMigrationError("v2 content already exists without an upgrade header");
|
|
138
|
+
}
|
|
139
|
+
header = value;
|
|
140
|
+
legacyBoundaryOffset = physical.start;
|
|
141
|
+
if (value.upgradedFrom!.boundaryOffset !== legacyBoundaryOffset) {
|
|
142
|
+
throw new LegacyTranscriptMigrationError("upgrade header legacy boundary offset is invalid");
|
|
143
|
+
}
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (!checkpointRecord) {
|
|
147
|
+
try {
|
|
148
|
+
validateTranscriptRecord(value, {
|
|
149
|
+
agentSessionId: header.agentSessionId,
|
|
150
|
+
logId: header.transcriptId,
|
|
151
|
+
generation: header.generation,
|
|
152
|
+
transcriptPath: undefined,
|
|
153
|
+
});
|
|
154
|
+
} catch (error) {
|
|
155
|
+
throw new LegacyTranscriptMigrationError("invalid initial checkpoint after upgrade header", { cause: error });
|
|
156
|
+
}
|
|
157
|
+
if (value.t !== "checkpoint" || value.seq !== 2) {
|
|
158
|
+
throw new LegacyTranscriptMigrationError("upgrade header is not followed by its initial checkpoint");
|
|
159
|
+
}
|
|
160
|
+
checkpointRecord = value;
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
// A completed migration may already have ordinary v2 append history. The migration
|
|
164
|
+
// boundary is still idempotently discoverable; ordinary open owns validating its tail.
|
|
165
|
+
}
|
|
166
|
+
if (header && header.seq !== 1) throw new LegacyTranscriptMigrationError("upgrade header sequence must be 1");
|
|
167
|
+
return { legacyBoundaryOffset, completeOffset, header, checkpointRecord };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function createUpgradeHeader(
|
|
171
|
+
options: MigrateLegacyTranscriptOptions,
|
|
172
|
+
boundaryOffset: number,
|
|
173
|
+
): TranscriptHeaderRecord {
|
|
174
|
+
const persistence = resolveDirectPersistence({
|
|
175
|
+
transcript: { path: options.path, ...options.transcript },
|
|
176
|
+
auditLog: false,
|
|
177
|
+
limits: options.limits,
|
|
178
|
+
});
|
|
179
|
+
if (persistence === false || persistence.transcript === false) {
|
|
180
|
+
throw new LegacyTranscriptMigrationError("migration transcript policy is disabled");
|
|
181
|
+
}
|
|
182
|
+
const createdAt = (options.now?.() ?? new Date()).toISOString();
|
|
183
|
+
const header: TranscriptHeaderRecord = {
|
|
184
|
+
v: 2,
|
|
185
|
+
t: "header",
|
|
186
|
+
transcriptId: options.transcriptId ?? randomUUID(),
|
|
187
|
+
generation: 1,
|
|
188
|
+
agentSessionId: options.agentSessionId,
|
|
189
|
+
seq: 1,
|
|
190
|
+
ts: Date.parse(createdAt),
|
|
191
|
+
event: "upgraded",
|
|
192
|
+
createdAt,
|
|
193
|
+
preset: persistence.transcript.preset,
|
|
194
|
+
effectivePolicy: persistence.transcript.capture,
|
|
195
|
+
effectiveLimits: persistence.limits,
|
|
196
|
+
includeTruncationDigests: persistence.transcript.includeTruncationDigests,
|
|
197
|
+
upgradedFrom: { version: 1, boundaryOffset },
|
|
198
|
+
};
|
|
199
|
+
validateTranscriptRecord(header);
|
|
200
|
+
return header;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function createMigrationCheckpoint(
|
|
204
|
+
options: MigrateLegacyTranscriptOptions,
|
|
205
|
+
header: TranscriptHeaderRecord,
|
|
206
|
+
incarnationId: string,
|
|
207
|
+
): AgentSessionCheckpoint {
|
|
208
|
+
const continuation = options.continuation;
|
|
209
|
+
return createAgentSessionCheckpoint({
|
|
210
|
+
agentSessionId: options.agentSessionId,
|
|
211
|
+
incarnationId,
|
|
212
|
+
stateRevision: 1,
|
|
213
|
+
adapterId: continuation.adapterId,
|
|
214
|
+
mode: continuation.mode,
|
|
215
|
+
internalSessionId: continuation.internalSessionId,
|
|
216
|
+
internalSessionActivatedAt: continuation.internalSessionActivatedAt,
|
|
217
|
+
internalSessionHistoryRevision: 0,
|
|
218
|
+
internalSessionHistoryDigest: EMPTY_HISTORY_DIGEST,
|
|
219
|
+
model: continuation.model,
|
|
220
|
+
sessionConfiguration: continuation.sessionConfiguration,
|
|
221
|
+
protocol: continuation.protocol,
|
|
222
|
+
transcript: {
|
|
223
|
+
transcriptId: header.transcriptId,
|
|
224
|
+
generation: 1,
|
|
225
|
+
path: options.path,
|
|
226
|
+
coveredSequence: 1,
|
|
227
|
+
},
|
|
228
|
+
boundary: { status: "settled", lastSettledOperationId: null },
|
|
229
|
+
updatedAt: header.createdAt,
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function checkpointRecord(
|
|
234
|
+
header: TranscriptHeaderRecord,
|
|
235
|
+
checkpoint: AgentSessionCheckpoint,
|
|
236
|
+
): TranscriptCheckpointRecord {
|
|
237
|
+
const record: TranscriptCheckpointRecord = {
|
|
238
|
+
v: 2,
|
|
239
|
+
t: "checkpoint",
|
|
240
|
+
transcriptId: header.transcriptId,
|
|
241
|
+
generation: 1,
|
|
242
|
+
agentSessionId: header.agentSessionId,
|
|
243
|
+
seq: 2,
|
|
244
|
+
ts: header.ts,
|
|
245
|
+
stateRevision: 1,
|
|
246
|
+
checkpoint,
|
|
247
|
+
};
|
|
248
|
+
validateTranscriptRecord(record, {
|
|
249
|
+
agentSessionId: header.agentSessionId,
|
|
250
|
+
logId: header.transcriptId,
|
|
251
|
+
generation: 1,
|
|
252
|
+
transcriptPath: checkpoint.transcript?.path,
|
|
253
|
+
});
|
|
254
|
+
return record;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function assertExistingMatches(
|
|
258
|
+
header: TranscriptHeaderRecord,
|
|
259
|
+
record: TranscriptCheckpointRecord,
|
|
260
|
+
options: MigrateLegacyTranscriptOptions,
|
|
261
|
+
): void {
|
|
262
|
+
assertHeaderRequestMatches(header, options);
|
|
263
|
+
const expected = createMigrationCheckpoint(options, header, record.checkpoint.incarnationId);
|
|
264
|
+
if (canonicalizeJson(expected) !== canonicalizeJson(record.checkpoint)) {
|
|
265
|
+
throw new LegacyTranscriptMigrationError("existing migration checkpoint disagrees with supplied continuation");
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function assertHeaderRequestMatches(header: TranscriptHeaderRecord, options: MigrateLegacyTranscriptOptions): void {
|
|
270
|
+
if (header.agentSessionId !== options.agentSessionId) {
|
|
271
|
+
throw new LegacyTranscriptMigrationError("existing upgrade belongs to another agent session");
|
|
272
|
+
}
|
|
273
|
+
if (options.transcriptId !== undefined && header.transcriptId !== options.transcriptId) {
|
|
274
|
+
throw new LegacyTranscriptMigrationError("existing upgrade transcriptId disagrees with request");
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function freezeResult(
|
|
279
|
+
status: LegacyTranscriptMigrationResult["status"],
|
|
280
|
+
header: TranscriptHeaderRecord,
|
|
281
|
+
checkpoint: AgentSessionCheckpoint,
|
|
282
|
+
): LegacyTranscriptMigrationResult {
|
|
283
|
+
return Object.freeze({
|
|
284
|
+
status,
|
|
285
|
+
header: structuredClone(header),
|
|
286
|
+
checkpoint: structuredClone(checkpoint),
|
|
287
|
+
legacyBoundaryOffset: header.upgradedFrom!.boundaryOffset,
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function validateOptions(options: MigrateLegacyTranscriptOptions): void {
|
|
292
|
+
if (!isAbsolute(options.path)) throw new LegacyTranscriptMigrationError("migration path must be absolute");
|
|
293
|
+
if (!options.agentSessionId.trim()) throw new LegacyTranscriptMigrationError("agentSessionId must not be blank");
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function isRecord(value: unknown): value is Record<string, any> {
|
|
297
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
298
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import type { Stats } from "node:fs";
|
|
2
|
+
import { lstat as lstatAsync } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { isAbsolute, join, parse, resolve, sep } from "node:path";
|
|
5
|
+
import {
|
|
6
|
+
PersistenceConfigurationError,
|
|
7
|
+
type PersistenceRootEnvironment,
|
|
8
|
+
type ResolvedAgentSessionPersistence,
|
|
9
|
+
} from "./config.ts";
|
|
10
|
+
|
|
11
|
+
export interface ResolvedSessionLogPaths {
|
|
12
|
+
readonly transcriptPath: string | null;
|
|
13
|
+
readonly auditLogPath: string | null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
interface ResolvedFile {
|
|
17
|
+
readonly path: string;
|
|
18
|
+
readonly identity: string | null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Resolve filesystem-dependent transcript/audit destinations without creating them. */
|
|
22
|
+
export async function resolveSessionLogPaths(
|
|
23
|
+
persistence: ResolvedAgentSessionPersistence,
|
|
24
|
+
agentSessionId: string,
|
|
25
|
+
environment: PersistenceRootEnvironment = {},
|
|
26
|
+
): Promise<ResolvedSessionLogPaths> {
|
|
27
|
+
if (!agentSessionId.trim()) {
|
|
28
|
+
throw new PersistenceConfigurationError("agentSessionId cannot be blank for persistence");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const encodedId = encodeURIComponent(agentSessionId);
|
|
32
|
+
const transcript = persistence.transcript === false
|
|
33
|
+
? null
|
|
34
|
+
: await resolveLogPath(
|
|
35
|
+
persistence.transcript.path,
|
|
36
|
+
join(persistence.root, "transcripts", `${encodedId}.jsonl`),
|
|
37
|
+
encodedId,
|
|
38
|
+
environment,
|
|
39
|
+
"transcript",
|
|
40
|
+
);
|
|
41
|
+
const auditLog = persistence.auditLog === false
|
|
42
|
+
? null
|
|
43
|
+
: await resolveLogPath(
|
|
44
|
+
persistence.auditLog.path,
|
|
45
|
+
join(persistence.root, "audit-logs", `${encodedId}.jsonl`),
|
|
46
|
+
encodedId,
|
|
47
|
+
environment,
|
|
48
|
+
"audit log",
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
if (
|
|
52
|
+
transcript &&
|
|
53
|
+
auditLog &&
|
|
54
|
+
(transcript.path === auditLog.path ||
|
|
55
|
+
(transcript.identity !== null && transcript.identity === auditLog.identity))
|
|
56
|
+
) {
|
|
57
|
+
throw new PersistenceConfigurationError(
|
|
58
|
+
"transcript and audit log must resolve to different files",
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return Object.freeze({
|
|
63
|
+
transcriptPath: transcript?.path ?? null,
|
|
64
|
+
auditLogPath: auditLog?.path ?? null,
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function resolveLogPath(
|
|
69
|
+
configuredPath: string | undefined,
|
|
70
|
+
defaultFile: string,
|
|
71
|
+
encodedAgentSessionId: string,
|
|
72
|
+
environment: PersistenceRootEnvironment,
|
|
73
|
+
label: string,
|
|
74
|
+
): Promise<ResolvedFile> {
|
|
75
|
+
if (configuredPath === undefined) {
|
|
76
|
+
return inspectDesiredFile(defaultFile, label);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const normalized = normalizePath(configuredPath, environment);
|
|
80
|
+
const configured = await inspectPath(normalized, label);
|
|
81
|
+
if (configured.kind === "directory") {
|
|
82
|
+
return inspectDesiredFile(join(normalized, `${encodedAgentSessionId}.jsonl`), label);
|
|
83
|
+
}
|
|
84
|
+
if (configured.kind === "file") {
|
|
85
|
+
return { path: normalized, identity: fileIdentity(configured.stats) };
|
|
86
|
+
}
|
|
87
|
+
if (configured.kind === "missing") {
|
|
88
|
+
return { path: normalized, identity: null };
|
|
89
|
+
}
|
|
90
|
+
throw new PersistenceConfigurationError(`${label} path is not a regular file or directory`);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function inspectDesiredFile(path: string, label: string): Promise<ResolvedFile> {
|
|
94
|
+
const inspected = await inspectPath(path, label);
|
|
95
|
+
if (inspected.kind === "directory" || inspected.kind === "other") {
|
|
96
|
+
throw new PersistenceConfigurationError(`${label} destination is not a regular file`);
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
path,
|
|
100
|
+
identity: inspected.kind === "file" ? fileIdentity(inspected.stats) : null,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
type InspectedPath =
|
|
105
|
+
| { kind: "missing" }
|
|
106
|
+
| { kind: "file"; stats: Stats }
|
|
107
|
+
| { kind: "directory"; stats: Stats }
|
|
108
|
+
| { kind: "other"; stats: Stats };
|
|
109
|
+
|
|
110
|
+
async function inspectPath(path: string, label: string): Promise<InspectedPath> {
|
|
111
|
+
await rejectExistingSymlinkComponents(path, label);
|
|
112
|
+
let stats: Stats;
|
|
113
|
+
try {
|
|
114
|
+
stats = await lstatAsync(path);
|
|
115
|
+
} catch (error) {
|
|
116
|
+
if (isMissing(error)) return { kind: "missing" };
|
|
117
|
+
throw new PersistenceConfigurationError(`${label} path cannot be inspected: ${errorMessage(error)}`);
|
|
118
|
+
}
|
|
119
|
+
if (stats.isSymbolicLink()) {
|
|
120
|
+
throw new PersistenceConfigurationError(`${label} path cannot be a symbolic link`);
|
|
121
|
+
}
|
|
122
|
+
if (stats.isFile()) return { kind: "file", stats };
|
|
123
|
+
if (stats.isDirectory()) return { kind: "directory", stats };
|
|
124
|
+
return { kind: "other", stats };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function rejectExistingSymlinkComponents(path: string, label: string): Promise<void> {
|
|
128
|
+
const { root } = parse(path);
|
|
129
|
+
const rest = path.slice(root.length).split(sep).filter(Boolean);
|
|
130
|
+
let current = root;
|
|
131
|
+
for (const component of rest) {
|
|
132
|
+
current = join(current, component);
|
|
133
|
+
try {
|
|
134
|
+
const stats = await lstatAsync(current);
|
|
135
|
+
if (stats.isSymbolicLink()) {
|
|
136
|
+
throw new PersistenceConfigurationError(`${label} path crosses a symbolic link: ${current}`);
|
|
137
|
+
}
|
|
138
|
+
} catch (error) {
|
|
139
|
+
if (error instanceof PersistenceConfigurationError) throw error;
|
|
140
|
+
if (isMissing(error)) return;
|
|
141
|
+
throw new PersistenceConfigurationError(
|
|
142
|
+
`${label} path component cannot be inspected: ${errorMessage(error)}`,
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function normalizePath(value: string, environment: PersistenceRootEnvironment): string {
|
|
149
|
+
const home = environment.home ?? homedir();
|
|
150
|
+
const cwd = environment.cwd ?? process.cwd();
|
|
151
|
+
const expanded = value === "~"
|
|
152
|
+
? home
|
|
153
|
+
: value.startsWith("~/")
|
|
154
|
+
? join(home, value.slice(2))
|
|
155
|
+
: value;
|
|
156
|
+
if (expanded.startsWith("~")) {
|
|
157
|
+
throw new PersistenceConfigurationError("session-log paths support only ~ or ~/ expansion");
|
|
158
|
+
}
|
|
159
|
+
return isAbsolute(expanded) ? resolve(expanded) : resolve(cwd, expanded);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function fileIdentity(stats: Stats): string {
|
|
163
|
+
return `${stats.dev}:${stats.ino}`;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function isMissing(error: unknown): boolean {
|
|
167
|
+
return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function errorMessage(error: unknown): string {
|
|
171
|
+
return error instanceof Error ? error.message : String(error);
|
|
172
|
+
}
|