@nones/agentflow-core 0.1.0 → 0.6.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/LICENSE +21 -0
- package/README.md +179 -0
- package/package.json +16 -2
- package/src/artifact-history.ts +853 -0
- package/src/client.ts +92 -1
- package/src/engine.ts +2382 -97
- package/src/history.ts +1268 -0
- package/src/ids.ts +3 -0
- package/src/index.ts +46 -3
- package/src/inspection.ts +1580 -0
- package/src/protocol.ts +165 -0
- package/src/server.ts +544 -56
- package/src/session-configuration.ts +82 -0
- package/src/store.ts +956 -20
- package/src/types.ts +484 -2
- package/src/validation.ts +458 -1
|
@@ -0,0 +1,853 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable artifact version history.
|
|
3
|
+
*
|
|
4
|
+
* Declared artifacts keep a single current row in the existing `artifacts`
|
|
5
|
+
* table (owned by `Store`). This module adds an append-only version history next
|
|
6
|
+
* to it: every successful stage becomes an immutable version carrying its
|
|
7
|
+
* origin (phase/round/agent/attempt), a verified SHA-256 digest and, for `file`
|
|
8
|
+
* artifacts, a private copy of the bytes under the owner-only artifact root so
|
|
9
|
+
* later versions cannot overwrite an earlier one.
|
|
10
|
+
*
|
|
11
|
+
* Boundaries:
|
|
12
|
+
* - it is a small helper, not a second store: it takes an explicit, open
|
|
13
|
+
* `bun:sqlite` `Database` so callers can run it inside their own transaction;
|
|
14
|
+
* - output validation and file containment stay in `prepareArtifact`, which is
|
|
15
|
+
* reused unchanged here (no duplicate check);
|
|
16
|
+
* - only files that `prepareArtifact` already accepted as inside the producing
|
|
17
|
+
* agent's cwd are copied, and the digest is recomputed from the bytes actually
|
|
18
|
+
* written, so an unverified copy is never recorded;
|
|
19
|
+
* - the durable row is written only after the file/version staging succeeds, so
|
|
20
|
+
* a failure leaves neither a version nor a leaked staging file;
|
|
21
|
+
* - previews are bounded and truncated with an explicit state, and `table`/
|
|
22
|
+
* `html` values are treated as inert data, never rendered.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import type { Database, SQLQueryBindings } from "bun:sqlite";
|
|
26
|
+
import { createHash, getRandomValues } from "node:crypto";
|
|
27
|
+
import {
|
|
28
|
+
chmodSync,
|
|
29
|
+
lstatSync,
|
|
30
|
+
mkdirSync,
|
|
31
|
+
openSync,
|
|
32
|
+
closeSync,
|
|
33
|
+
readFileSync,
|
|
34
|
+
readSync,
|
|
35
|
+
renameSync,
|
|
36
|
+
rmSync,
|
|
37
|
+
writeFileSync,
|
|
38
|
+
} from "node:fs";
|
|
39
|
+
import { join, relative, sep } from "node:path";
|
|
40
|
+
import { prepareArtifact } from "./artifacts";
|
|
41
|
+
import { AgentFlowError } from "./errors";
|
|
42
|
+
import { fromJson, toJson } from "./json";
|
|
43
|
+
import type { ArtifactDeclaration } from "./types";
|
|
44
|
+
|
|
45
|
+
/** Default retained preview bytes. */
|
|
46
|
+
export const ARTIFACT_PREVIEW_DEFAULT_BYTES = 4_096;
|
|
47
|
+
/** Hard maximum preview bytes; a caller cannot ask for more. */
|
|
48
|
+
export const ARTIFACT_PREVIEW_MAX_BYTES = 64 * 1_024;
|
|
49
|
+
/** Private staging directory name inside the owner-only root. */
|
|
50
|
+
const STAGING_DIR = ".staging";
|
|
51
|
+
|
|
52
|
+
/** Where a version came from and who produced it. */
|
|
53
|
+
export interface ArtifactOrigin {
|
|
54
|
+
/** Plan phase id; absent for a 0.1.1 wave-derived run. */
|
|
55
|
+
phaseId?: string;
|
|
56
|
+
/** Round id within the phase; absent when the run has no explicit rounds. */
|
|
57
|
+
roundId?: string;
|
|
58
|
+
/** Producing agent id. */
|
|
59
|
+
agentId: string;
|
|
60
|
+
/** Attempt (native submission) id; absent when the attempt is unknown. */
|
|
61
|
+
attemptId?: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface ArtifactVersionOptions {
|
|
65
|
+
/** Owner-only root: staging and stored file copies live only under it. */
|
|
66
|
+
root: string;
|
|
67
|
+
/** Default retained preview bytes for this call; capped at the hard max. */
|
|
68
|
+
previewBytes?: number;
|
|
69
|
+
/** Clock for creation times; defaults to `Date.now`. */
|
|
70
|
+
now?: () => number;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export type ArtifactPreviewState =
|
|
74
|
+
"empty" | "complete" | "truncated" | "unsupported";
|
|
75
|
+
|
|
76
|
+
/** Bounded, safe-to-render preview. HTML is always returned as inert data. */
|
|
77
|
+
export interface ArtifactPreview {
|
|
78
|
+
state: ArtifactPreviewState;
|
|
79
|
+
/** Content type of `text`; absent for non-text previews. */
|
|
80
|
+
contentType?: string;
|
|
81
|
+
/** Bounded UTF-8 text; absent when only a structural summary exists. */
|
|
82
|
+
text?: string;
|
|
83
|
+
/** Bytes retained in `text`. */
|
|
84
|
+
retainedBytes: number;
|
|
85
|
+
/** Full size when known; absent when it could not be determined. */
|
|
86
|
+
size?: number;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** One immutable stored version. */
|
|
90
|
+
export interface ArtifactVersion {
|
|
91
|
+
version: number;
|
|
92
|
+
id: string;
|
|
93
|
+
runId: string;
|
|
94
|
+
artifactId: string;
|
|
95
|
+
declaration: ArtifactDeclaration;
|
|
96
|
+
/** `staged` or `invalid`; a version is only written after a real outcome. */
|
|
97
|
+
state: "staged" | "invalid";
|
|
98
|
+
origin: ArtifactOrigin;
|
|
99
|
+
/** Lowercase hex SHA-256 of the exact stored bytes; absent for invalid output. */
|
|
100
|
+
digest?: string;
|
|
101
|
+
/** Bytes stored; absent for non-file artifacts and invalid output. */
|
|
102
|
+
size?: number;
|
|
103
|
+
/** Content type of the original bytes for file artifacts. */
|
|
104
|
+
contentType?: string;
|
|
105
|
+
/** Relative path of the private file copy under the root; file artifacts only. */
|
|
106
|
+
storedPath?: string;
|
|
107
|
+
error?: string;
|
|
108
|
+
createdAt: number;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export interface ArtifactStageResult {
|
|
112
|
+
state: "staged" | "invalid";
|
|
113
|
+
version: ArtifactVersion;
|
|
114
|
+
preview: ArtifactPreview;
|
|
115
|
+
/** Diagnostics that are not failures, e.g. why a preview is unsupported. */
|
|
116
|
+
notices: string[];
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export interface ArtifactCatalogueEntry {
|
|
120
|
+
artifactId: string;
|
|
121
|
+
declaration: ArtifactDeclaration;
|
|
122
|
+
versions: ArtifactVersion[];
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export interface ArtifactCatalogueOptions {
|
|
126
|
+
/** Keyset: return versions greater than this number. */
|
|
127
|
+
after?: number;
|
|
128
|
+
/** Maximum versions per artifact; default 100, hard max 500. */
|
|
129
|
+
limit?: number;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const CATALOGUE_DEFAULT_LIMIT = 100;
|
|
133
|
+
const CATALOGUE_MAX_LIMIT = 500;
|
|
134
|
+
const MAX_ID = 256;
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Additive tables owned by this capability. They share the SQLite file (and its
|
|
138
|
+
* transactionality and backups) but stay outside the `Store` schema version,
|
|
139
|
+
* which another owner maintains.
|
|
140
|
+
*/
|
|
141
|
+
const ARTIFACT_VERSION_DDL = `
|
|
142
|
+
CREATE TABLE IF NOT EXISTS artifact_versions (
|
|
143
|
+
id TEXT PRIMARY KEY,
|
|
144
|
+
run_id TEXT NOT NULL,
|
|
145
|
+
artifact_id TEXT NOT NULL,
|
|
146
|
+
version INTEGER NOT NULL,
|
|
147
|
+
declaration_json TEXT NOT NULL,
|
|
148
|
+
state TEXT NOT NULL,
|
|
149
|
+
phase_id TEXT,
|
|
150
|
+
round_id TEXT,
|
|
151
|
+
agent_id TEXT NOT NULL,
|
|
152
|
+
attempt_id TEXT,
|
|
153
|
+
digest TEXT,
|
|
154
|
+
size INTEGER,
|
|
155
|
+
content_type TEXT,
|
|
156
|
+
stored_path TEXT,
|
|
157
|
+
error TEXT,
|
|
158
|
+
created_at INTEGER NOT NULL,
|
|
159
|
+
UNIQUE (run_id, artifact_id, version)
|
|
160
|
+
);
|
|
161
|
+
CREATE INDEX IF NOT EXISTS artifact_versions_page_idx
|
|
162
|
+
ON artifact_versions (run_id, artifact_id, version);
|
|
163
|
+
CREATE TABLE IF NOT EXISTS artifact_version_previews (
|
|
164
|
+
version_id TEXT NOT NULL,
|
|
165
|
+
state TEXT NOT NULL,
|
|
166
|
+
content_type TEXT,
|
|
167
|
+
text TEXT,
|
|
168
|
+
retained_bytes INTEGER NOT NULL,
|
|
169
|
+
size INTEGER,
|
|
170
|
+
PRIMARY KEY (version_id)
|
|
171
|
+
);
|
|
172
|
+
`;
|
|
173
|
+
|
|
174
|
+
/** Create the additive tables if they do not exist yet. Idempotent. */
|
|
175
|
+
export function ensureArtifactVersionTables(db: Database): void {
|
|
176
|
+
db.exec(ARTIFACT_VERSION_DDL);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Validate that `root` is a real directory the owner can use privately.
|
|
181
|
+
*
|
|
182
|
+
* Returns an error string instead of throwing so the caller can turn it into a
|
|
183
|
+
* clean staged/invalid outcome. A symlinked root or a symlinked staging dir is
|
|
184
|
+
* rejected: writing through it could escape the owner-only tree.
|
|
185
|
+
*/
|
|
186
|
+
export function validateArtifactRoot(root: string): string | undefined {
|
|
187
|
+
if (typeof root !== "string" || root.trim() === "") {
|
|
188
|
+
return "artifact root is required";
|
|
189
|
+
}
|
|
190
|
+
let info;
|
|
191
|
+
try {
|
|
192
|
+
info = lstatSync(root);
|
|
193
|
+
} catch {
|
|
194
|
+
return `artifact root does not exist: ${root}`;
|
|
195
|
+
}
|
|
196
|
+
if (info.isSymbolicLink()) return `artifact root is a symlink: ${root}`;
|
|
197
|
+
if (!info.isDirectory()) return `artifact root is not a directory: ${root}`;
|
|
198
|
+
// Owner-only bits (0700). Shared/group-readable roots cannot hold private copies.
|
|
199
|
+
if ((Number(info.mode) & 0o077) !== 0) {
|
|
200
|
+
return `artifact root is not owner-only: ${root}`;
|
|
201
|
+
}
|
|
202
|
+
return undefined;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function safeId(value: unknown, label: string): string {
|
|
206
|
+
if (typeof value !== "string") {
|
|
207
|
+
throw new AgentFlowError("validation", `${label} must be a string`);
|
|
208
|
+
}
|
|
209
|
+
const trimmed = value.trim();
|
|
210
|
+
if (trimmed === "" || trimmed.length > MAX_ID) {
|
|
211
|
+
throw new AgentFlowError("validation", `${label} is empty or too long`);
|
|
212
|
+
}
|
|
213
|
+
if (/[\u0000-\u001f\u007f]/u.test(trimmed)) {
|
|
214
|
+
throw new AgentFlowError("validation", `${label} has control characters`);
|
|
215
|
+
}
|
|
216
|
+
return trimmed;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function optionalId(value: unknown, label: string): string | undefined {
|
|
220
|
+
return value === undefined ? undefined : safeId(value, label);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function boundedLimit(value: number | undefined): number {
|
|
224
|
+
const raw = value ?? CATALOGUE_DEFAULT_LIMIT;
|
|
225
|
+
return Math.max(1, Math.min(Math.floor(raw), CATALOGUE_MAX_LIMIT));
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function sha256(bytes: Uint8Array): string {
|
|
229
|
+
return createHash("sha256").update(bytes).digest("hex");
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function ensureInsideRoot(root: string, target: string): void {
|
|
233
|
+
const rel = relative(root, target);
|
|
234
|
+
if (rel === "" || rel.startsWith("..") || rel.startsWith(`..${sep}`)) {
|
|
235
|
+
throw new AgentFlowError(
|
|
236
|
+
"internal",
|
|
237
|
+
`refusing to write outside the artifact root: ${target}`,
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function contentKind(path: string): { contentType: string; text: boolean } {
|
|
243
|
+
const lower = path.toLowerCase();
|
|
244
|
+
if (lower.endsWith(".json"))
|
|
245
|
+
return { contentType: "application/json", text: true };
|
|
246
|
+
if (lower.endsWith(".md") || lower.endsWith(".markdown")) {
|
|
247
|
+
return { contentType: "text/markdown", text: true };
|
|
248
|
+
}
|
|
249
|
+
if (lower.endsWith(".html") || lower.endsWith(".htm")) {
|
|
250
|
+
return { contentType: "text/html", text: true };
|
|
251
|
+
}
|
|
252
|
+
if (
|
|
253
|
+
lower.endsWith(".txt") ||
|
|
254
|
+
lower.endsWith(".log") ||
|
|
255
|
+
lower.endsWith(".csv") ||
|
|
256
|
+
lower.endsWith(".tsv")
|
|
257
|
+
) {
|
|
258
|
+
return { contentType: "text/plain", text: true };
|
|
259
|
+
}
|
|
260
|
+
return { contentType: "application/octet-stream", text: false };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Bound a UTF-8 buffer to at most `max` bytes without splitting a code point. */
|
|
264
|
+
function boundUtf8(
|
|
265
|
+
bytes: Uint8Array,
|
|
266
|
+
max: number,
|
|
267
|
+
): { text: string; retainedBytes: number; state: "complete" | "truncated" } {
|
|
268
|
+
const decoded = new TextDecoder("utf-8");
|
|
269
|
+
if (bytes.byteLength <= max) {
|
|
270
|
+
return {
|
|
271
|
+
text: decoded.decode(bytes),
|
|
272
|
+
retainedBytes: bytes.byteLength,
|
|
273
|
+
state: "complete",
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
// Trim trailing continuation bytes so the truncated slice stays valid UTF-8.
|
|
277
|
+
let end = max;
|
|
278
|
+
while (end > 0 && (bytes[end]! & 0b1100_0000) === 0b1000_0000) end -= 1;
|
|
279
|
+
const slice = bytes.subarray(0, end);
|
|
280
|
+
return {
|
|
281
|
+
text: decoded.decode(slice),
|
|
282
|
+
retainedBytes: slice.byteLength,
|
|
283
|
+
state: "truncated",
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function previewBytesOf(options: ArtifactVersionOptions): number {
|
|
288
|
+
const raw = options.previewBytes ?? ARTIFACT_PREVIEW_DEFAULT_BYTES;
|
|
289
|
+
return Math.max(0, Math.min(Math.floor(raw), ARTIFACT_PREVIEW_MAX_BYTES));
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function buildPreview(
|
|
293
|
+
declaration: ArtifactDeclaration,
|
|
294
|
+
bytes: Uint8Array,
|
|
295
|
+
contentType: string | undefined,
|
|
296
|
+
maxBytes: number,
|
|
297
|
+
textCapable: boolean,
|
|
298
|
+
): ArtifactPreview {
|
|
299
|
+
// `table`/`html` arrive with the presentation types another owner adds to
|
|
300
|
+
// `types.ts`; handle them by name so this module compiles either way.
|
|
301
|
+
const type: string = declaration.type;
|
|
302
|
+
if (type === "table") {
|
|
303
|
+
// A table version keeps its size but never serializes rows into a preview.
|
|
304
|
+
return {
|
|
305
|
+
state: "unsupported",
|
|
306
|
+
retainedBytes: 0,
|
|
307
|
+
size: bytes.byteLength,
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
if (!textCapable || contentType === undefined) {
|
|
311
|
+
return {
|
|
312
|
+
state: bytes.byteLength === 0 ? "empty" : "unsupported",
|
|
313
|
+
retainedBytes: 0,
|
|
314
|
+
size: bytes.byteLength,
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
if (bytes.byteLength === 0) {
|
|
318
|
+
return { state: "empty", contentType, text: "", retainedBytes: 0, size: 0 };
|
|
319
|
+
}
|
|
320
|
+
const bounded = boundUtf8(bytes, maxBytes);
|
|
321
|
+
return {
|
|
322
|
+
state: bounded.retainedBytes === 0 ? "truncated" : bounded.state,
|
|
323
|
+
contentType,
|
|
324
|
+
text: bounded.text,
|
|
325
|
+
retainedBytes: bounded.retainedBytes,
|
|
326
|
+
size: bytes.byteLength,
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* Serialize a non-file value to canonical bytes for its declaration.
|
|
332
|
+
*
|
|
333
|
+
* `text` keeps the exact string; `json` and `table` use core's `toJson` so the
|
|
334
|
+
* digest matches what would be persisted; `html` is stored as inert text and
|
|
335
|
+
* never sanitized or rendered here.
|
|
336
|
+
*/
|
|
337
|
+
function nonFileBytes(
|
|
338
|
+
declaration: ArtifactDeclaration,
|
|
339
|
+
value: unknown,
|
|
340
|
+
): { bytes: Uint8Array; contentType: string } {
|
|
341
|
+
const encoder = new TextEncoder();
|
|
342
|
+
const type: string = declaration.type;
|
|
343
|
+
if (type === "text") {
|
|
344
|
+
return {
|
|
345
|
+
bytes: encoder.encode(typeof value === "string" ? value : String(value)),
|
|
346
|
+
contentType: "text/plain",
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
if (type === "html") {
|
|
350
|
+
return {
|
|
351
|
+
bytes: encoder.encode(typeof value === "string" ? value : toJson(value)),
|
|
352
|
+
contentType: "text/html",
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
// json and table.
|
|
356
|
+
return {
|
|
357
|
+
bytes: encoder.encode(toJson(value)),
|
|
358
|
+
contentType: "application/json",
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
interface StageInput {
|
|
363
|
+
db: Database;
|
|
364
|
+
runId: string;
|
|
365
|
+
declaration: ArtifactDeclaration;
|
|
366
|
+
/** Raw value exactly as the producer returned it. */
|
|
367
|
+
raw: unknown;
|
|
368
|
+
/** Producing agent cwd; passed to `prepareArtifact` for file containment. */
|
|
369
|
+
cwd: string;
|
|
370
|
+
origin: ArtifactOrigin;
|
|
371
|
+
options: ArtifactVersionOptions;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Stage one artifact outcome and append an immutable version.
|
|
376
|
+
*
|
|
377
|
+
* Runs entirely inside the caller's `Database`; wrap the call in the caller's
|
|
378
|
+
* own transaction when the surrounding `artifacts` row must move atomically with
|
|
379
|
+
* it. File artifacts are copied to the root before the row is written.
|
|
380
|
+
*/
|
|
381
|
+
export function stageArtifactVersion(input: StageInput): ArtifactStageResult {
|
|
382
|
+
const { db, declaration, raw, cwd, options } = input;
|
|
383
|
+
ensureArtifactVersionTables(db);
|
|
384
|
+
|
|
385
|
+
const runId = safeId(input.runId, "run id");
|
|
386
|
+
const artifactId = safeId(declaration?.id, "artifact id");
|
|
387
|
+
const phaseId = optionalId(input.origin?.phaseId, "origin phase id");
|
|
388
|
+
const roundId = optionalId(input.origin?.roundId, "origin round id");
|
|
389
|
+
const attemptId = optionalId(input.origin?.attemptId, "origin attempt id");
|
|
390
|
+
const origin: ArtifactOrigin = {
|
|
391
|
+
agentId: safeId(input.origin?.agentId, "origin agent id"),
|
|
392
|
+
...(phaseId === undefined ? {} : { phaseId }),
|
|
393
|
+
...(roundId === undefined ? {} : { roundId }),
|
|
394
|
+
...(attemptId === undefined ? {} : { attemptId }),
|
|
395
|
+
};
|
|
396
|
+
|
|
397
|
+
// Reuse the existing, unchanged validation and file containment.
|
|
398
|
+
const prepared = prepareArtifact(declaration, raw, cwd);
|
|
399
|
+
const now = options.now?.() ?? Date.now();
|
|
400
|
+
const notices: string[] = [];
|
|
401
|
+
const maxBytes = previewBytesOf(options);
|
|
402
|
+
|
|
403
|
+
if (prepared.state === "invalid") {
|
|
404
|
+
const version = appendVersion(db, {
|
|
405
|
+
runId,
|
|
406
|
+
artifactId,
|
|
407
|
+
declaration,
|
|
408
|
+
state: "invalid",
|
|
409
|
+
origin,
|
|
410
|
+
error: prepared.error ?? "artifact is invalid",
|
|
411
|
+
createdAt: now,
|
|
412
|
+
});
|
|
413
|
+
const preview: ArtifactPreview = { state: "unsupported", retainedBytes: 0 };
|
|
414
|
+
storePreview(db, version.id, preview);
|
|
415
|
+
return { state: "invalid", version, preview, notices };
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
let bytes: Uint8Array;
|
|
419
|
+
let contentType: string;
|
|
420
|
+
let storedPath: string | undefined;
|
|
421
|
+
let textCapable = true;
|
|
422
|
+
// Allocate the next version number once: it names the file copy and the row.
|
|
423
|
+
const versionNumber = nextVersionNumber(db, runId, artifactId) + 1;
|
|
424
|
+
|
|
425
|
+
if (declaration.type === "file") {
|
|
426
|
+
if (prepared.path === undefined) {
|
|
427
|
+
throw new AgentFlowError(
|
|
428
|
+
"internal",
|
|
429
|
+
`prepared file artifact ${artifactId} has no path`,
|
|
430
|
+
);
|
|
431
|
+
}
|
|
432
|
+
let originalBytes: Uint8Array;
|
|
433
|
+
try {
|
|
434
|
+
originalBytes = new Uint8Array(readFileSync(prepared.path));
|
|
435
|
+
} catch {
|
|
436
|
+
// The file vanished or became unreadable between validation and read.
|
|
437
|
+
const version = appendVersion(db, {
|
|
438
|
+
runId,
|
|
439
|
+
artifactId,
|
|
440
|
+
declaration,
|
|
441
|
+
state: "invalid",
|
|
442
|
+
origin,
|
|
443
|
+
error: "artifact file is no longer available",
|
|
444
|
+
createdAt: now,
|
|
445
|
+
});
|
|
446
|
+
const preview: ArtifactPreview = {
|
|
447
|
+
state: "unsupported",
|
|
448
|
+
retainedBytes: 0,
|
|
449
|
+
};
|
|
450
|
+
storePreview(db, version.id, preview);
|
|
451
|
+
return { state: "invalid", version, preview, notices };
|
|
452
|
+
}
|
|
453
|
+
const rootError = validateArtifactRoot(options.root);
|
|
454
|
+
if (rootError !== undefined) {
|
|
455
|
+
throw new AgentFlowError("validation", rootError);
|
|
456
|
+
}
|
|
457
|
+
const kind = contentKind(prepared.path);
|
|
458
|
+
contentType = kind.contentType;
|
|
459
|
+
textCapable = kind.text;
|
|
460
|
+
const staged = writeStagedFile(options.root, originalBytes);
|
|
461
|
+
try {
|
|
462
|
+
const stored = storeVersionFile(
|
|
463
|
+
options.root,
|
|
464
|
+
storedPathFor(runId, artifactId, versionNumber),
|
|
465
|
+
staged,
|
|
466
|
+
);
|
|
467
|
+
// Digest is recomputed from the bytes that actually landed on disk.
|
|
468
|
+
bytes = stored.bytes;
|
|
469
|
+
storedPath = stored.relativePath;
|
|
470
|
+
} finally {
|
|
471
|
+
// `rename` consumed the staging file; remove only if it survived.
|
|
472
|
+
removeIfPresent(staged);
|
|
473
|
+
}
|
|
474
|
+
} else {
|
|
475
|
+
const encoded = nonFileBytes(declaration, prepared.value);
|
|
476
|
+
bytes = encoded.bytes;
|
|
477
|
+
contentType = encoded.contentType;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
const digest = sha256(bytes);
|
|
481
|
+
const version = appendVersion(db, {
|
|
482
|
+
runId,
|
|
483
|
+
artifactId,
|
|
484
|
+
declaration,
|
|
485
|
+
state: "staged",
|
|
486
|
+
origin,
|
|
487
|
+
version: versionNumber,
|
|
488
|
+
digest,
|
|
489
|
+
size: bytes.byteLength,
|
|
490
|
+
contentType,
|
|
491
|
+
...(storedPath === undefined ? {} : { storedPath }),
|
|
492
|
+
createdAt: now,
|
|
493
|
+
});
|
|
494
|
+
const preview = buildPreview(
|
|
495
|
+
declaration,
|
|
496
|
+
bytes,
|
|
497
|
+
contentType,
|
|
498
|
+
maxBytes,
|
|
499
|
+
textCapable,
|
|
500
|
+
);
|
|
501
|
+
if (preview.state === "truncated") {
|
|
502
|
+
notices.push(
|
|
503
|
+
`preview truncated to ${preview.retainedBytes} of ${preview.size ?? "?"} bytes`,
|
|
504
|
+
);
|
|
505
|
+
}
|
|
506
|
+
if (
|
|
507
|
+
preview.state === "unsupported" &&
|
|
508
|
+
(declaration.type as string) === "table"
|
|
509
|
+
) {
|
|
510
|
+
notices.push("table preview serializes a structural summary only");
|
|
511
|
+
}
|
|
512
|
+
storePreview(db, version.id, preview);
|
|
513
|
+
return { state: "staged", version, preview, notices };
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
function storedPathFor(
|
|
517
|
+
runId: string,
|
|
518
|
+
artifactId: string,
|
|
519
|
+
version: number,
|
|
520
|
+
): string {
|
|
521
|
+
// Flat, filesystem-safe leaf; ids are already control-character free.
|
|
522
|
+
const safe = (value: string) => value.replace(/[^A-Za-z0-9._-]/gu, "_");
|
|
523
|
+
return join("versions", safe(runId), safe(artifactId), `${version}.bin`);
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
function writeStagedFile(root: string, bytes: Uint8Array): string {
|
|
527
|
+
const stagingDir = join(root, STAGING_DIR);
|
|
528
|
+
mkdirSync(stagingDir, { recursive: true, mode: 0o700 });
|
|
529
|
+
ensureInsideRoot(root, stagingDir);
|
|
530
|
+
const leaf = cryptoRandomLeaf();
|
|
531
|
+
const staged = join(stagingDir, leaf);
|
|
532
|
+
const fd = openSync(staged, "wx", 0o600);
|
|
533
|
+
try {
|
|
534
|
+
writeFileSync(fd, bytes);
|
|
535
|
+
} finally {
|
|
536
|
+
closeSync(fd);
|
|
537
|
+
}
|
|
538
|
+
chmodSync(staged, 0o600);
|
|
539
|
+
return staged;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
function cryptoRandomLeaf(): string {
|
|
543
|
+
// 16 random bytes as hex; avoids a dependency and collisions in practice.
|
|
544
|
+
const random = new Uint8Array(16);
|
|
545
|
+
getRandomValues(random);
|
|
546
|
+
return Array.from(random, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
function storeVersionFile(
|
|
550
|
+
root: string,
|
|
551
|
+
relativePath: string,
|
|
552
|
+
staged: string,
|
|
553
|
+
): { relativePath: string; bytes: Uint8Array } {
|
|
554
|
+
const target = join(root, relativePath);
|
|
555
|
+
mkdirSync(join(target, ".."), { recursive: true, mode: 0o700 });
|
|
556
|
+
ensureInsideRoot(root, target);
|
|
557
|
+
// Atomic replace within the same filesystem, then read back to verify.
|
|
558
|
+
try {
|
|
559
|
+
renameSync(staged, target);
|
|
560
|
+
} catch {
|
|
561
|
+
// Fall back to a same-dir copy-then-rename so the final path is atomic too.
|
|
562
|
+
const bytes = new Uint8Array(readFileSync(staged));
|
|
563
|
+
const fallback = `${target}.${cryptoRandomLeaf()}`;
|
|
564
|
+
writeFileSync(fallback, bytes, { mode: 0o600 });
|
|
565
|
+
renameSync(fallback, target);
|
|
566
|
+
}
|
|
567
|
+
chmodSync(target, 0o600);
|
|
568
|
+
const bytes = new Uint8Array(readFileSync(target));
|
|
569
|
+
return { relativePath, bytes };
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function removeIfPresent(path: string): void {
|
|
573
|
+
try {
|
|
574
|
+
rmSync(path, { force: false });
|
|
575
|
+
} catch {
|
|
576
|
+
// Already renamed into place; nothing to clean up.
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
interface AppendInput {
|
|
581
|
+
runId: string;
|
|
582
|
+
artifactId: string;
|
|
583
|
+
declaration: ArtifactDeclaration;
|
|
584
|
+
state: "staged" | "invalid";
|
|
585
|
+
origin: ArtifactOrigin;
|
|
586
|
+
/** Fixed version number; when omitted the next free number is allocated. */
|
|
587
|
+
version?: number;
|
|
588
|
+
digest?: string;
|
|
589
|
+
size?: number;
|
|
590
|
+
contentType?: string;
|
|
591
|
+
storedPath?: string;
|
|
592
|
+
error?: string;
|
|
593
|
+
createdAt: number;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
function nextVersionNumber(
|
|
597
|
+
db: Database,
|
|
598
|
+
runId: string,
|
|
599
|
+
artifactId: string,
|
|
600
|
+
): number {
|
|
601
|
+
const row = db
|
|
602
|
+
.query<{ version: number | null }, [string, string]>(
|
|
603
|
+
`SELECT MAX(version) AS version FROM artifact_versions
|
|
604
|
+
WHERE run_id = ? AND artifact_id = ?`,
|
|
605
|
+
)
|
|
606
|
+
.get(runId, artifactId);
|
|
607
|
+
return row?.version ?? 0;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
function appendVersion(db: Database, input: AppendInput): ArtifactVersion {
|
|
611
|
+
const version =
|
|
612
|
+
input.version ?? nextVersionNumber(db, input.runId, input.artifactId) + 1;
|
|
613
|
+
const id = `${input.runId}:${input.artifactId}:${version}`;
|
|
614
|
+
db.query(
|
|
615
|
+
`INSERT INTO artifact_versions
|
|
616
|
+
(id, run_id, artifact_id, version, declaration_json, state, phase_id,
|
|
617
|
+
round_id, agent_id, attempt_id, digest, size, content_type, stored_path,
|
|
618
|
+
error, created_at)
|
|
619
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
620
|
+
).run(
|
|
621
|
+
id,
|
|
622
|
+
input.runId,
|
|
623
|
+
input.artifactId,
|
|
624
|
+
version,
|
|
625
|
+
toJson(input.declaration),
|
|
626
|
+
input.state,
|
|
627
|
+
input.origin.phaseId ?? null,
|
|
628
|
+
input.origin.roundId ?? null,
|
|
629
|
+
input.origin.agentId,
|
|
630
|
+
input.origin.attemptId ?? null,
|
|
631
|
+
input.digest ?? null,
|
|
632
|
+
input.size ?? null,
|
|
633
|
+
input.contentType ?? null,
|
|
634
|
+
input.storedPath ?? null,
|
|
635
|
+
input.error ?? null,
|
|
636
|
+
input.createdAt,
|
|
637
|
+
);
|
|
638
|
+
return {
|
|
639
|
+
version,
|
|
640
|
+
id,
|
|
641
|
+
runId: input.runId,
|
|
642
|
+
artifactId: input.artifactId,
|
|
643
|
+
declaration: input.declaration,
|
|
644
|
+
state: input.state,
|
|
645
|
+
origin: input.origin,
|
|
646
|
+
...(input.digest === undefined ? {} : { digest: input.digest }),
|
|
647
|
+
...(input.size === undefined ? {} : { size: input.size }),
|
|
648
|
+
...(input.contentType === undefined
|
|
649
|
+
? {}
|
|
650
|
+
: { contentType: input.contentType }),
|
|
651
|
+
...(input.storedPath === undefined ? {} : { storedPath: input.storedPath }),
|
|
652
|
+
...(input.error === undefined ? {} : { error: input.error }),
|
|
653
|
+
createdAt: input.createdAt,
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
function storePreview(
|
|
658
|
+
db: Database,
|
|
659
|
+
versionId: string,
|
|
660
|
+
preview: ArtifactPreview,
|
|
661
|
+
): void {
|
|
662
|
+
db.query(
|
|
663
|
+
`INSERT INTO artifact_version_previews
|
|
664
|
+
(version_id, state, content_type, text, retained_bytes, size)
|
|
665
|
+
VALUES (?, ?, ?, ?, ?, ?)`,
|
|
666
|
+
).run(
|
|
667
|
+
versionId,
|
|
668
|
+
preview.state,
|
|
669
|
+
preview.contentType ?? null,
|
|
670
|
+
preview.text ?? null,
|
|
671
|
+
preview.retainedBytes,
|
|
672
|
+
preview.size ?? null,
|
|
673
|
+
);
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
interface VersionRow {
|
|
677
|
+
id: string;
|
|
678
|
+
run_id: string;
|
|
679
|
+
artifact_id: string;
|
|
680
|
+
version: number;
|
|
681
|
+
declaration_json: string;
|
|
682
|
+
state: "staged" | "invalid";
|
|
683
|
+
phase_id: string | null;
|
|
684
|
+
round_id: string | null;
|
|
685
|
+
agent_id: string;
|
|
686
|
+
attempt_id: string | null;
|
|
687
|
+
digest: string | null;
|
|
688
|
+
size: number | null;
|
|
689
|
+
content_type: string | null;
|
|
690
|
+
stored_path: string | null;
|
|
691
|
+
error: string | null;
|
|
692
|
+
created_at: number;
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
function rowToVersion(row: VersionRow): ArtifactVersion {
|
|
696
|
+
const declaration = fromJson<ArtifactDeclaration>(row.declaration_json, {
|
|
697
|
+
id: row.artifact_id,
|
|
698
|
+
type: "text",
|
|
699
|
+
});
|
|
700
|
+
return {
|
|
701
|
+
version: row.version,
|
|
702
|
+
id: row.id,
|
|
703
|
+
runId: row.run_id,
|
|
704
|
+
artifactId: row.artifact_id,
|
|
705
|
+
declaration,
|
|
706
|
+
state: row.state,
|
|
707
|
+
origin: {
|
|
708
|
+
agentId: row.agent_id,
|
|
709
|
+
...(row.phase_id === null ? {} : { phaseId: row.phase_id }),
|
|
710
|
+
...(row.round_id === null ? {} : { roundId: row.round_id }),
|
|
711
|
+
...(row.attempt_id === null ? {} : { attemptId: row.attempt_id }),
|
|
712
|
+
},
|
|
713
|
+
...(row.digest === null ? {} : { digest: row.digest }),
|
|
714
|
+
...(row.size === null ? {} : { size: row.size }),
|
|
715
|
+
...(row.content_type === null ? {} : { contentType: row.content_type }),
|
|
716
|
+
...(row.stored_path === null ? {} : { storedPath: row.stored_path }),
|
|
717
|
+
...(row.error === null ? {} : { error: row.error }),
|
|
718
|
+
createdAt: row.created_at,
|
|
719
|
+
};
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/**
|
|
723
|
+
* Read the version catalogue for one run, newest-last per artifact, bounded by
|
|
724
|
+
* `limit`. Read-only; does not create tables. Safe against an offline database
|
|
725
|
+
* that was opened `readonly: true`.
|
|
726
|
+
*/
|
|
727
|
+
export function listArtifactVersions(
|
|
728
|
+
db: Database,
|
|
729
|
+
runId: string,
|
|
730
|
+
options: ArtifactCatalogueOptions = {},
|
|
731
|
+
): ArtifactCatalogueEntry[] {
|
|
732
|
+
const limit = boundedLimit(options.limit);
|
|
733
|
+
const after = Math.max(0, Math.floor(options.after ?? 0));
|
|
734
|
+
const rows = db
|
|
735
|
+
.query<VersionRow, [string, number, number]>(
|
|
736
|
+
`SELECT * FROM artifact_versions
|
|
737
|
+
WHERE run_id = ? AND version > ?
|
|
738
|
+
ORDER BY artifact_id ASC, version ASC
|
|
739
|
+
LIMIT ?`,
|
|
740
|
+
)
|
|
741
|
+
.all(runId, after, limit);
|
|
742
|
+
const grouped = new Map<string, ArtifactCatalogueEntry>();
|
|
743
|
+
for (const row of rows) {
|
|
744
|
+
const version = rowToVersion(row);
|
|
745
|
+
const entry = grouped.get(version.artifactId);
|
|
746
|
+
if (entry === undefined) {
|
|
747
|
+
grouped.set(version.artifactId, {
|
|
748
|
+
artifactId: version.artifactId,
|
|
749
|
+
declaration: version.declaration,
|
|
750
|
+
versions: [version],
|
|
751
|
+
});
|
|
752
|
+
continue;
|
|
753
|
+
}
|
|
754
|
+
entry.versions.push(version);
|
|
755
|
+
}
|
|
756
|
+
return [...grouped.values()];
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/** Read one stored version including its bounded preview, if any. */
|
|
760
|
+
export function readArtifactVersion(
|
|
761
|
+
db: Database,
|
|
762
|
+
runId: string,
|
|
763
|
+
artifactId: string,
|
|
764
|
+
version: number,
|
|
765
|
+
): { version: ArtifactVersion; preview?: ArtifactPreview } | undefined {
|
|
766
|
+
const row = db
|
|
767
|
+
.query<VersionRow, [string, string, number]>(
|
|
768
|
+
`SELECT * FROM artifact_versions
|
|
769
|
+
WHERE run_id = ? AND artifact_id = ? AND version = ?`,
|
|
770
|
+
)
|
|
771
|
+
.get(runId, artifactId, version);
|
|
772
|
+
if (row === undefined || row === null) return undefined;
|
|
773
|
+
const stored = rowToVersion(row);
|
|
774
|
+
const previewRow = db
|
|
775
|
+
.query<
|
|
776
|
+
{
|
|
777
|
+
state: ArtifactPreviewState;
|
|
778
|
+
content_type: string | null;
|
|
779
|
+
text: string | null;
|
|
780
|
+
retained_bytes: number;
|
|
781
|
+
size: number | null;
|
|
782
|
+
},
|
|
783
|
+
[string]
|
|
784
|
+
>(`SELECT * FROM artifact_version_previews WHERE version_id = ?`)
|
|
785
|
+
.get(stored.id);
|
|
786
|
+
const preview: ArtifactPreview | undefined =
|
|
787
|
+
previewRow === undefined || previewRow === null
|
|
788
|
+
? undefined
|
|
789
|
+
: {
|
|
790
|
+
state: previewRow.state,
|
|
791
|
+
...(previewRow.content_type === null
|
|
792
|
+
? {}
|
|
793
|
+
: { contentType: previewRow.content_type }),
|
|
794
|
+
...(previewRow.text === null ? {} : { text: previewRow.text }),
|
|
795
|
+
retainedBytes: previewRow.retained_bytes,
|
|
796
|
+
...(previewRow.size === null ? {} : { size: previewRow.size }),
|
|
797
|
+
};
|
|
798
|
+
return { version: stored, ...(preview === undefined ? {} : { preview }) };
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
/**
|
|
802
|
+
* Verify a stored file version still matches its recorded digest. Returns
|
|
803
|
+
* `false` for non-file versions, a missing copy, or any mismatch — never throws —
|
|
804
|
+
* so an inspector can show an untrusted state instead of crashing.
|
|
805
|
+
*/
|
|
806
|
+
export function verifyStoredArtifactVersion(
|
|
807
|
+
root: string,
|
|
808
|
+
version: ArtifactVersion,
|
|
809
|
+
): boolean {
|
|
810
|
+
if (version.storedPath === undefined || version.digest === undefined) {
|
|
811
|
+
return false;
|
|
812
|
+
}
|
|
813
|
+
const target = join(root, version.storedPath);
|
|
814
|
+
try {
|
|
815
|
+
const rel = relative(root, target);
|
|
816
|
+
if (rel === "" || rel.startsWith("..") || rel.startsWith(`..${sep}`)) {
|
|
817
|
+
return false;
|
|
818
|
+
}
|
|
819
|
+
const bytes = readFileSync(target);
|
|
820
|
+
return sha256(new Uint8Array(bytes)) === version.digest;
|
|
821
|
+
} catch {
|
|
822
|
+
return false;
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/** Read up to `maxBytes` from a stored file version for a fresh bounded preview. */
|
|
827
|
+
export function readStoredArtifactBytes(
|
|
828
|
+
root: string,
|
|
829
|
+
version: ArtifactVersion,
|
|
830
|
+
maxBytes = ARTIFACT_PREVIEW_DEFAULT_BYTES,
|
|
831
|
+
): Uint8Array | undefined {
|
|
832
|
+
if (version.storedPath === undefined) return undefined;
|
|
833
|
+
const target = join(root, version.storedPath);
|
|
834
|
+
const rel = relative(root, target);
|
|
835
|
+
if (rel === "" || rel.startsWith("..") || rel.startsWith(`..${sep}`)) {
|
|
836
|
+
return undefined;
|
|
837
|
+
}
|
|
838
|
+
const cap = Math.max(
|
|
839
|
+
0,
|
|
840
|
+
Math.min(Math.floor(maxBytes), ARTIFACT_PREVIEW_MAX_BYTES),
|
|
841
|
+
);
|
|
842
|
+
let fd: number | undefined;
|
|
843
|
+
try {
|
|
844
|
+
fd = openSync(target, "r");
|
|
845
|
+
const buffer = new Uint8Array(cap);
|
|
846
|
+
const read = readSync(fd, buffer, 0, cap, 0);
|
|
847
|
+
return buffer.subarray(0, read);
|
|
848
|
+
} catch {
|
|
849
|
+
return undefined;
|
|
850
|
+
} finally {
|
|
851
|
+
if (fd !== undefined) closeSync(fd);
|
|
852
|
+
}
|
|
853
|
+
}
|