@agent-inspect/studio 6.31.37 → 6.31.39
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/dist/index.cjs +2341 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +290 -0
- package/dist/index.d.ts +290 -0
- package/dist/index.mjs +2307 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +2 -2
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,2307 @@
|
|
|
1
|
+
import { readFile, access, readdir, writeFile, rm, copyFile, mkdir, rename, mkdtemp, lstat, stat } from 'fs/promises';
|
|
2
|
+
import path10 from 'path';
|
|
3
|
+
import { loadSessionRunRecords, buildSessionIndex, runSuite, buildRunTimeline, extractOutcomesFromTraceEvents, resolveTraceDir, searchTraces, TraceDirectory, loadTraceMetadataList } from 'agent-inspect/advanced';
|
|
4
|
+
import { resolveWorkspaceLocation, readWorkspaceManifestFile } from 'agent-inspect/workspace';
|
|
5
|
+
import { mkdirSync, createReadStream } from 'fs';
|
|
6
|
+
import { createRequire } from 'module';
|
|
7
|
+
import { timingSafeEqual, createHash } from 'crypto';
|
|
8
|
+
import { createServer } from 'http';
|
|
9
|
+
import { runTraceChecks, createRunStatusRule } from 'agent-inspect/checks';
|
|
10
|
+
import { diffRuns, manualTraceEventsToComparableRun } from 'agent-inspect/diff';
|
|
11
|
+
import { persistedInspectEventsToTraceEvents } from 'agent-inspect/persisted';
|
|
12
|
+
import { openTrace } from 'agent-inspect/readers';
|
|
13
|
+
|
|
14
|
+
// packages/studio/src/registry.ts
|
|
15
|
+
function isSafeRelativePath(p) {
|
|
16
|
+
const trimmed = p.trim();
|
|
17
|
+
if (trimmed === "" || trimmed.startsWith("/") || trimmed.startsWith("\\")) return false;
|
|
18
|
+
if (/^[a-zA-Z]:/.test(trimmed)) return false;
|
|
19
|
+
return !trimmed.split(/[/\\]+/).some((seg) => seg === "..");
|
|
20
|
+
}
|
|
21
|
+
function resolveUnderRoot(root, ...segments) {
|
|
22
|
+
const resolvedRoot = path10.resolve(root);
|
|
23
|
+
const resolved = path10.resolve(resolvedRoot, ...segments);
|
|
24
|
+
assertPathUnderRoot(resolved, resolvedRoot);
|
|
25
|
+
return resolved;
|
|
26
|
+
}
|
|
27
|
+
function assertPathUnderRoot(resolved, root) {
|
|
28
|
+
const rel = path10.relative(path10.resolve(root), path10.resolve(resolved));
|
|
29
|
+
if (rel.startsWith("..") || path10.isAbsolute(rel)) {
|
|
30
|
+
throw new Error("path escapes allowed registry root");
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// packages/studio/src/registry.ts
|
|
35
|
+
var STUDIO_REGISTRY_SCHEMA_VERSION = "1.0";
|
|
36
|
+
var STUDIO_REGISTRY_FILENAMES = [
|
|
37
|
+
"studio-registry.json",
|
|
38
|
+
".agent-inspect/studio-registry.json"
|
|
39
|
+
];
|
|
40
|
+
var MAX_REGISTRY_BYTES = 256 * 1024;
|
|
41
|
+
function isPlainObject(value) {
|
|
42
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
43
|
+
}
|
|
44
|
+
function parseStudioRegistry(input) {
|
|
45
|
+
const errors = [];
|
|
46
|
+
if (!isPlainObject(input)) {
|
|
47
|
+
return { ok: false, errors: ["registry must be a JSON object"], warnings: [] };
|
|
48
|
+
}
|
|
49
|
+
if (input.schemaVersion !== STUDIO_REGISTRY_SCHEMA_VERSION) {
|
|
50
|
+
errors.push(`schemaVersion must be "${STUDIO_REGISTRY_SCHEMA_VERSION}"`);
|
|
51
|
+
}
|
|
52
|
+
if (typeof input.name !== "string" || input.name.trim() === "") {
|
|
53
|
+
errors.push("name must be a non-empty string");
|
|
54
|
+
}
|
|
55
|
+
if (!Array.isArray(input.projects) || input.projects.length === 0) {
|
|
56
|
+
errors.push("projects must be a non-empty array");
|
|
57
|
+
}
|
|
58
|
+
const projects = [];
|
|
59
|
+
if (Array.isArray(input.projects)) {
|
|
60
|
+
for (const [index, item] of input.projects.entries()) {
|
|
61
|
+
if (!isPlainObject(item)) {
|
|
62
|
+
errors.push(`projects[${index}] must be an object`);
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
const id = typeof item.id === "string" ? item.id.trim() : "";
|
|
66
|
+
const projectPath = typeof item.path === "string" ? item.path.trim() : "";
|
|
67
|
+
if (!id) errors.push(`projects[${index}].id must be a non-empty string`);
|
|
68
|
+
if (!projectPath) errors.push(`projects[${index}].path must be a non-empty string`);
|
|
69
|
+
const label = typeof item.label === "string" ? item.label.trim() : void 0;
|
|
70
|
+
const suiteConfigs = Array.isArray(item.suiteConfigs) ? item.suiteConfigs.filter((value) => typeof value === "string") : void 0;
|
|
71
|
+
projects.push({
|
|
72
|
+
id,
|
|
73
|
+
path: projectPath,
|
|
74
|
+
...label ? { label } : {},
|
|
75
|
+
...suiteConfigs && suiteConfigs.length > 0 ? { suiteConfigs } : {}
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
let importConfig;
|
|
80
|
+
if (input.import !== void 0) {
|
|
81
|
+
if (!isPlainObject(input.import)) {
|
|
82
|
+
errors.push("import must be an object");
|
|
83
|
+
} else {
|
|
84
|
+
importConfig = {};
|
|
85
|
+
if (input.import.ciArtifactsDir !== void 0) {
|
|
86
|
+
const dir = String(input.import.ciArtifactsDir).trim();
|
|
87
|
+
if (!isSafeRelativePath(dir)) {
|
|
88
|
+
errors.push("import.ciArtifactsDir must be a safe relative path");
|
|
89
|
+
} else {
|
|
90
|
+
importConfig.ciArtifactsDir = dir;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (input.import.bundlesDir !== void 0) {
|
|
94
|
+
const dir = String(input.import.bundlesDir).trim();
|
|
95
|
+
if (!isSafeRelativePath(dir)) {
|
|
96
|
+
errors.push("import.bundlesDir must be a safe relative path");
|
|
97
|
+
} else {
|
|
98
|
+
importConfig.bundlesDir = dir;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (input.import.fileDropDir !== void 0) {
|
|
102
|
+
const dir = String(input.import.fileDropDir).trim();
|
|
103
|
+
if (!isSafeRelativePath(dir)) {
|
|
104
|
+
errors.push("import.fileDropDir must be a safe relative path");
|
|
105
|
+
} else {
|
|
106
|
+
importConfig.fileDropDir = dir;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (input.import.enabled !== void 0) {
|
|
110
|
+
if (typeof input.import.enabled !== "boolean") {
|
|
111
|
+
errors.push("import.enabled must be a boolean");
|
|
112
|
+
} else {
|
|
113
|
+
importConfig.enabled = input.import.enabled;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
let ingestConfig;
|
|
119
|
+
const ingestWarnings = [];
|
|
120
|
+
if (input.ingest !== void 0) {
|
|
121
|
+
if (!isPlainObject(input.ingest)) {
|
|
122
|
+
errors.push("ingest must be an object");
|
|
123
|
+
} else {
|
|
124
|
+
ingestConfig = {};
|
|
125
|
+
if (input.ingest.github !== void 0) {
|
|
126
|
+
if (!isPlainObject(input.ingest.github)) {
|
|
127
|
+
errors.push("ingest.github must be an object");
|
|
128
|
+
} else {
|
|
129
|
+
const github = {};
|
|
130
|
+
if (input.ingest.github.enabled !== void 0) {
|
|
131
|
+
if (typeof input.ingest.github.enabled !== "boolean") {
|
|
132
|
+
errors.push("ingest.github.enabled must be a boolean");
|
|
133
|
+
} else {
|
|
134
|
+
github.enabled = input.ingest.github.enabled;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (input.ingest.github.tokenEnv !== void 0) {
|
|
138
|
+
const tokenEnv = String(input.ingest.github.tokenEnv).trim();
|
|
139
|
+
if (!/^[A-Z][A-Z0-9_]*$/.test(tokenEnv)) {
|
|
140
|
+
errors.push("ingest.github.tokenEnv must be an uppercase env var name");
|
|
141
|
+
} else {
|
|
142
|
+
github.tokenEnv = tokenEnv;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
ingestConfig.github = github;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (input.ingest.http !== void 0) {
|
|
149
|
+
if (!isPlainObject(input.ingest.http)) {
|
|
150
|
+
errors.push("ingest.http must be an object");
|
|
151
|
+
} else {
|
|
152
|
+
const http = {};
|
|
153
|
+
if (input.ingest.http.enabled !== void 0) {
|
|
154
|
+
if (typeof input.ingest.http.enabled !== "boolean") {
|
|
155
|
+
errors.push("ingest.http.enabled must be a boolean");
|
|
156
|
+
} else {
|
|
157
|
+
http.enabled = input.ingest.http.enabled;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (input.ingest.http.path !== void 0) {
|
|
161
|
+
const ingestPath = String(input.ingest.http.path).trim();
|
|
162
|
+
if (!ingestPath.startsWith("/") || ingestPath.includes("..")) {
|
|
163
|
+
errors.push("ingest.http.path must be an absolute safe path");
|
|
164
|
+
} else {
|
|
165
|
+
http.path = ingestPath;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (input.ingest.http.tokenEnv !== void 0) {
|
|
169
|
+
const tokenEnv = String(input.ingest.http.tokenEnv).trim();
|
|
170
|
+
if (!/^[A-Z][A-Z0-9_]*$/.test(tokenEnv)) {
|
|
171
|
+
errors.push("ingest.http.tokenEnv must be an uppercase env var name");
|
|
172
|
+
} else {
|
|
173
|
+
http.tokenEnv = tokenEnv;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
if (input.ingest.http.maxBytes !== void 0) {
|
|
177
|
+
const maxBytes = Number(input.ingest.http.maxBytes);
|
|
178
|
+
if (!Number.isInteger(maxBytes) || maxBytes <= 0) {
|
|
179
|
+
errors.push("ingest.http.maxBytes must be a positive integer");
|
|
180
|
+
} else {
|
|
181
|
+
http.maxBytes = maxBytes;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
ingestConfig.http = http;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
if (input.ingest.bundleUpload !== void 0) {
|
|
188
|
+
if (!isPlainObject(input.ingest.bundleUpload)) {
|
|
189
|
+
errors.push("ingest.bundleUpload must be an object");
|
|
190
|
+
} else {
|
|
191
|
+
const bundleUpload = {};
|
|
192
|
+
if (input.ingest.bundleUpload.enabled !== void 0) {
|
|
193
|
+
if (typeof input.ingest.bundleUpload.enabled !== "boolean") {
|
|
194
|
+
errors.push("ingest.bundleUpload.enabled must be a boolean");
|
|
195
|
+
} else {
|
|
196
|
+
bundleUpload.enabled = input.ingest.bundleUpload.enabled;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (input.ingest.bundleUpload.maxBytes !== void 0) {
|
|
200
|
+
const maxBytes = Number(input.ingest.bundleUpload.maxBytes);
|
|
201
|
+
if (!Number.isInteger(maxBytes) || maxBytes <= 0) {
|
|
202
|
+
errors.push("ingest.bundleUpload.maxBytes must be a positive integer");
|
|
203
|
+
} else {
|
|
204
|
+
bundleUpload.maxBytes = maxBytes;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
ingestConfig.bundleUpload = bundleUpload;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
if (input.ingest.fileDrop !== void 0) {
|
|
211
|
+
if (!isPlainObject(input.ingest.fileDrop)) {
|
|
212
|
+
errors.push("ingest.fileDrop must be an object");
|
|
213
|
+
} else {
|
|
214
|
+
const fileDrop = {};
|
|
215
|
+
if (input.ingest.fileDrop.maxBytes !== void 0) {
|
|
216
|
+
const maxBytes = Number(input.ingest.fileDrop.maxBytes);
|
|
217
|
+
if (!Number.isInteger(maxBytes) || maxBytes <= 0) {
|
|
218
|
+
errors.push("ingest.fileDrop.maxBytes must be a positive integer");
|
|
219
|
+
} else {
|
|
220
|
+
fileDrop.maxBytes = maxBytes;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
ingestConfig.fileDrop = fileDrop;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
const knownIngestKeys = /* @__PURE__ */ new Set(["github", "http", "bundleUpload", "fileDrop"]);
|
|
227
|
+
for (const key of Object.keys(input.ingest)) {
|
|
228
|
+
if (!knownIngestKeys.has(key)) {
|
|
229
|
+
ingestWarnings.push(`ignored unknown ingest key: ${key}`);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (errors.length > 0) return { ok: false, errors, warnings: ingestWarnings };
|
|
235
|
+
return {
|
|
236
|
+
ok: true,
|
|
237
|
+
registry: {
|
|
238
|
+
schemaVersion: STUDIO_REGISTRY_SCHEMA_VERSION,
|
|
239
|
+
name: String(input.name).trim(),
|
|
240
|
+
projects,
|
|
241
|
+
...importConfig ? { import: importConfig } : {},
|
|
242
|
+
...ingestConfig ? { ingest: ingestConfig } : {}
|
|
243
|
+
},
|
|
244
|
+
errors: [],
|
|
245
|
+
warnings: ingestWarnings
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
async function readStudioRegistryFile(filePath) {
|
|
249
|
+
try {
|
|
250
|
+
const raw = await readFile(filePath, "utf8");
|
|
251
|
+
if (raw.length > MAX_REGISTRY_BYTES) {
|
|
252
|
+
return {
|
|
253
|
+
ok: false,
|
|
254
|
+
path: filePath,
|
|
255
|
+
errors: ["registry file exceeds size limit"],
|
|
256
|
+
warnings: []
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
const parsed = parseStudioRegistry(JSON.parse(raw));
|
|
260
|
+
return { ...parsed, path: filePath };
|
|
261
|
+
} catch (error) {
|
|
262
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
263
|
+
return { ok: false, path: filePath, errors: [message], warnings: [] };
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
function resolveRegistryProjectPath(registryDir, projectPath) {
|
|
267
|
+
return path10.isAbsolute(projectPath) ? path10.resolve(projectPath) : path10.resolve(registryDir, projectPath);
|
|
268
|
+
}
|
|
269
|
+
var cached;
|
|
270
|
+
function loadBetterSqlite3() {
|
|
271
|
+
if (cached !== void 0) return cached;
|
|
272
|
+
try {
|
|
273
|
+
const require2 = createRequire(import.meta.url);
|
|
274
|
+
cached = require2("better-sqlite3");
|
|
275
|
+
return cached;
|
|
276
|
+
} catch (error) {
|
|
277
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
278
|
+
throw new Error(
|
|
279
|
+
`better-sqlite3 native driver is unavailable (${detail}). Install a prebuild for your Node/OS (see better-sqlite3 docs) or use filesystem-only AgentInspect paths without Studio persistence. Core agent-inspect remains usable without this optional package.`
|
|
280
|
+
);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// packages/studio/src/db.ts
|
|
285
|
+
var STUDIO_DB_SCHEMA_VERSION = "1.0";
|
|
286
|
+
var DEFAULT_STUDIO_DB_FILENAME = "studio.db";
|
|
287
|
+
var SCHEMA_SQL = `
|
|
288
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
289
|
+
key TEXT PRIMARY KEY,
|
|
290
|
+
value TEXT NOT NULL
|
|
291
|
+
);
|
|
292
|
+
CREATE TABLE IF NOT EXISTS projects (
|
|
293
|
+
id TEXT PRIMARY KEY,
|
|
294
|
+
label TEXT,
|
|
295
|
+
path TEXT NOT NULL,
|
|
296
|
+
workspace_dir TEXT NOT NULL,
|
|
297
|
+
project_name TEXT,
|
|
298
|
+
redaction_profile TEXT,
|
|
299
|
+
trace_count INTEGER NOT NULL DEFAULT 0,
|
|
300
|
+
imported_at TEXT NOT NULL
|
|
301
|
+
);
|
|
302
|
+
CREATE TABLE IF NOT EXISTS runs (
|
|
303
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
304
|
+
project_id TEXT NOT NULL,
|
|
305
|
+
run_id TEXT NOT NULL,
|
|
306
|
+
name TEXT,
|
|
307
|
+
status TEXT,
|
|
308
|
+
file TEXT,
|
|
309
|
+
started_at REAL,
|
|
310
|
+
duration_ms REAL,
|
|
311
|
+
session_id TEXT,
|
|
312
|
+
UNIQUE(project_id, run_id)
|
|
313
|
+
);
|
|
314
|
+
CREATE INDEX IF NOT EXISTS idx_runs_project ON runs(project_id);
|
|
315
|
+
CREATE INDEX IF NOT EXISTS idx_runs_status ON runs(status);
|
|
316
|
+
CREATE TABLE IF NOT EXISTS ingest_files (
|
|
317
|
+
source_key TEXT PRIMARY KEY,
|
|
318
|
+
source_name TEXT NOT NULL,
|
|
319
|
+
dest_path TEXT NOT NULL,
|
|
320
|
+
kind TEXT NOT NULL CHECK(kind IN ('ci', 'bundle')),
|
|
321
|
+
content_hash TEXT NOT NULL,
|
|
322
|
+
imported_at TEXT NOT NULL
|
|
323
|
+
);
|
|
324
|
+
CREATE INDEX IF NOT EXISTS idx_ingest_files_kind ON ingest_files(kind);
|
|
325
|
+
`;
|
|
326
|
+
function resolveStudioDbPath(options) {
|
|
327
|
+
if (options.dbPath && options.dbPath.trim() !== "") {
|
|
328
|
+
const raw = options.dbPath.trim();
|
|
329
|
+
if (raw.startsWith("postgres://") || raw.startsWith("postgresql://")) {
|
|
330
|
+
return raw;
|
|
331
|
+
}
|
|
332
|
+
return path10.resolve(options.cwd ?? process.cwd(), raw);
|
|
333
|
+
}
|
|
334
|
+
return path10.resolve(
|
|
335
|
+
options.cwd ?? process.cwd(),
|
|
336
|
+
".agent-inspect",
|
|
337
|
+
DEFAULT_STUDIO_DB_FILENAME
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
function isPostgresDbPath(dbPath) {
|
|
341
|
+
return dbPath.startsWith("postgres://") || dbPath.startsWith("postgresql://");
|
|
342
|
+
}
|
|
343
|
+
function openStudioDb(dbPath) {
|
|
344
|
+
if (isPostgresDbPath(dbPath)) {
|
|
345
|
+
throw new Error(
|
|
346
|
+
"Postgres studio databases are not supported; use a SQLite file path (preview only)."
|
|
347
|
+
);
|
|
348
|
+
}
|
|
349
|
+
const dir = path10.dirname(dbPath);
|
|
350
|
+
try {
|
|
351
|
+
mkdirSync(dir, { recursive: true });
|
|
352
|
+
} catch (error) {
|
|
353
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
354
|
+
throw new Error(`Failed to create studio database directory: ${message}`);
|
|
355
|
+
}
|
|
356
|
+
const Sqlite = loadBetterSqlite3();
|
|
357
|
+
const db = new Sqlite(dbPath);
|
|
358
|
+
db.pragma("journal_mode = WAL");
|
|
359
|
+
db.exec(SCHEMA_SQL);
|
|
360
|
+
const insertMeta = db.prepare(
|
|
361
|
+
"INSERT INTO meta(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
|
|
362
|
+
);
|
|
363
|
+
insertMeta.run("schemaVersion", STUDIO_DB_SCHEMA_VERSION);
|
|
364
|
+
insertMeta.run("driver", "better-sqlite3");
|
|
365
|
+
return db;
|
|
366
|
+
}
|
|
367
|
+
function upsertStudioProject(db, row) {
|
|
368
|
+
db.prepare(
|
|
369
|
+
`INSERT INTO projects(id, label, path, workspace_dir, project_name, redaction_profile, trace_count, imported_at)
|
|
370
|
+
VALUES (@id, @label, @path, @workspaceDir, @projectName, @redactionProfile, @traceCount, @importedAt)
|
|
371
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
372
|
+
label = excluded.label,
|
|
373
|
+
path = excluded.path,
|
|
374
|
+
workspace_dir = excluded.workspace_dir,
|
|
375
|
+
project_name = excluded.project_name,
|
|
376
|
+
redaction_profile = excluded.redaction_profile,
|
|
377
|
+
trace_count = excluded.trace_count,
|
|
378
|
+
imported_at = excluded.imported_at`
|
|
379
|
+
).run({
|
|
380
|
+
id: row.id,
|
|
381
|
+
label: row.label,
|
|
382
|
+
path: row.path,
|
|
383
|
+
workspaceDir: row.workspaceDir,
|
|
384
|
+
projectName: row.projectName,
|
|
385
|
+
redactionProfile: row.redactionProfile,
|
|
386
|
+
traceCount: row.traceCount,
|
|
387
|
+
importedAt: row.importedAt
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
function replaceProjectRuns(db, projectId, runs) {
|
|
391
|
+
const tx = db.transaction(() => {
|
|
392
|
+
db.prepare("DELETE FROM runs WHERE project_id = ?").run(projectId);
|
|
393
|
+
const insert = db.prepare(
|
|
394
|
+
`INSERT INTO runs(project_id, run_id, name, status, file, started_at, duration_ms, session_id)
|
|
395
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
|
|
396
|
+
);
|
|
397
|
+
for (const run of runs) {
|
|
398
|
+
insert.run(
|
|
399
|
+
projectId,
|
|
400
|
+
run.runId,
|
|
401
|
+
run.name ?? null,
|
|
402
|
+
run.status ?? null,
|
|
403
|
+
run.file ?? null,
|
|
404
|
+
run.startedAt ?? null,
|
|
405
|
+
run.durationMs ?? null,
|
|
406
|
+
run.sessionId ?? null
|
|
407
|
+
);
|
|
408
|
+
}
|
|
409
|
+
});
|
|
410
|
+
tx();
|
|
411
|
+
}
|
|
412
|
+
function getStudioProject(db, projectId) {
|
|
413
|
+
return db.prepare(
|
|
414
|
+
`SELECT id, label, path, workspace_dir AS workspaceDir, project_name AS projectName,
|
|
415
|
+
redaction_profile AS redactionProfile, trace_count AS traceCount, imported_at AS importedAt
|
|
416
|
+
FROM projects WHERE id = ?`
|
|
417
|
+
).get(projectId);
|
|
418
|
+
}
|
|
419
|
+
function listProjectRuns(db, projectId, limit = 200) {
|
|
420
|
+
const rows = db.prepare(
|
|
421
|
+
`SELECT project_id AS projectId, run_id AS runId, name, status, file,
|
|
422
|
+
started_at AS startedAt, duration_ms AS durationMs, session_id AS sessionId
|
|
423
|
+
FROM runs WHERE project_id = ? ORDER BY started_at DESC LIMIT ?`
|
|
424
|
+
).all(projectId, limit);
|
|
425
|
+
return rows;
|
|
426
|
+
}
|
|
427
|
+
function searchProjectRuns(db, projectId, query, limit = 50) {
|
|
428
|
+
const pattern = `%${query}%`;
|
|
429
|
+
return db.prepare(
|
|
430
|
+
`SELECT project_id AS projectId, run_id AS runId, name, status, file,
|
|
431
|
+
started_at AS startedAt, duration_ms AS durationMs, session_id AS sessionId
|
|
432
|
+
FROM runs
|
|
433
|
+
WHERE project_id = ?
|
|
434
|
+
AND (run_id LIKE ? OR IFNULL(name, '') LIKE ? OR IFNULL(status, '') LIKE ?)
|
|
435
|
+
ORDER BY started_at DESC
|
|
436
|
+
LIMIT ?`
|
|
437
|
+
).all(projectId, pattern, pattern, pattern, limit);
|
|
438
|
+
}
|
|
439
|
+
function findIngestFileBySourceKey(db, sourceKey) {
|
|
440
|
+
return db.prepare(
|
|
441
|
+
`SELECT source_key AS sourceKey, source_name AS sourceName, dest_path AS destPath,
|
|
442
|
+
kind, content_hash AS contentHash, imported_at AS importedAt
|
|
443
|
+
FROM ingest_files WHERE source_key = ?`
|
|
444
|
+
).get(sourceKey);
|
|
445
|
+
}
|
|
446
|
+
function insertIngestFile(db, row) {
|
|
447
|
+
db.prepare(
|
|
448
|
+
`INSERT INTO ingest_files(source_key, source_name, dest_path, kind, content_hash, imported_at)
|
|
449
|
+
VALUES (@sourceKey, @sourceName, @destPath, @kind, @contentHash, @importedAt)
|
|
450
|
+
ON CONFLICT(source_key) DO UPDATE SET
|
|
451
|
+
source_name = excluded.source_name,
|
|
452
|
+
dest_path = excluded.dest_path,
|
|
453
|
+
kind = excluded.kind,
|
|
454
|
+
content_hash = excluded.content_hash,
|
|
455
|
+
imported_at = excluded.imported_at`
|
|
456
|
+
).run(row);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// packages/studio/src/import.ts
|
|
460
|
+
async function discoverSuiteConfigs(projectRoot, configured) {
|
|
461
|
+
if (configured && configured.length > 0) {
|
|
462
|
+
return configured.map((rel) => path10.resolve(projectRoot, rel));
|
|
463
|
+
}
|
|
464
|
+
const found = [];
|
|
465
|
+
try {
|
|
466
|
+
const entries = await readdir(projectRoot);
|
|
467
|
+
for (const entry of entries) {
|
|
468
|
+
if (entry.endsWith(".suite.json")) {
|
|
469
|
+
found.push(path10.join(projectRoot, entry));
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
} catch {
|
|
473
|
+
}
|
|
474
|
+
return found.sort();
|
|
475
|
+
}
|
|
476
|
+
async function loadProjectRuns(workspaceDir, traceDirs) {
|
|
477
|
+
const runs = [];
|
|
478
|
+
for (const rel of traceDirs) {
|
|
479
|
+
const traceDir = resolveTraceDir({ dir: path10.join(workspaceDir, rel) });
|
|
480
|
+
const td = new TraceDirectory({ dir: traceDir });
|
|
481
|
+
const files = await td.list();
|
|
482
|
+
const metas = await loadTraceMetadataList(
|
|
483
|
+
traceDir,
|
|
484
|
+
files,
|
|
485
|
+
(fileName) => td.getPath(fileName)
|
|
486
|
+
);
|
|
487
|
+
for (const meta of metas) {
|
|
488
|
+
runs.push({
|
|
489
|
+
projectId: "",
|
|
490
|
+
runId: meta.runId,
|
|
491
|
+
...meta.name !== void 0 ? { name: meta.name } : {},
|
|
492
|
+
status: meta.status,
|
|
493
|
+
file: path10.basename(meta.filePath),
|
|
494
|
+
...meta.startedAt !== void 0 ? { startedAt: meta.startedAt } : {},
|
|
495
|
+
...meta.durationMs !== void 0 ? { durationMs: meta.durationMs } : {}
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
return runs.sort((a, b) => (b.startedAt ?? 0) - (a.startedAt ?? 0));
|
|
500
|
+
}
|
|
501
|
+
async function importStudioRegistry(options) {
|
|
502
|
+
const registryDir = path10.dirname(options.registryPath);
|
|
503
|
+
const warnings = [];
|
|
504
|
+
const projects = [];
|
|
505
|
+
const importedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
506
|
+
for (const project of options.registry.projects) {
|
|
507
|
+
const imported = await importStudioProject({
|
|
508
|
+
db: options.db,
|
|
509
|
+
registryDir,
|
|
510
|
+
project,
|
|
511
|
+
importedAt,
|
|
512
|
+
warnings
|
|
513
|
+
});
|
|
514
|
+
if (imported) projects.push(imported);
|
|
515
|
+
}
|
|
516
|
+
return {
|
|
517
|
+
registryName: options.registry.name,
|
|
518
|
+
projects,
|
|
519
|
+
warnings
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
async function importStudioProject(options) {
|
|
523
|
+
const projectRoot = resolveRegistryProjectPath(
|
|
524
|
+
options.registryDir,
|
|
525
|
+
options.project.path
|
|
526
|
+
);
|
|
527
|
+
const location = resolveWorkspaceLocation(projectRoot);
|
|
528
|
+
const manifestRead = await readWorkspaceManifestFile(location);
|
|
529
|
+
if (!manifestRead.ok || manifestRead.manifest === void 0) {
|
|
530
|
+
options.warnings.push(
|
|
531
|
+
`project "${options.project.id}": ${manifestRead.errors.join("; ") || "workspace.json missing"}`
|
|
532
|
+
);
|
|
533
|
+
return void 0;
|
|
534
|
+
}
|
|
535
|
+
const runs = await loadProjectRuns(
|
|
536
|
+
location.workspaceDir,
|
|
537
|
+
manifestRead.manifest.traceDirs
|
|
538
|
+
);
|
|
539
|
+
const suiteConfigPaths = await discoverSuiteConfigs(
|
|
540
|
+
projectRoot,
|
|
541
|
+
options.project.suiteConfigs
|
|
542
|
+
);
|
|
543
|
+
const row = {
|
|
544
|
+
id: options.project.id,
|
|
545
|
+
label: options.project.label ?? options.project.id,
|
|
546
|
+
path: projectRoot,
|
|
547
|
+
workspaceDir: location.workspaceDir,
|
|
548
|
+
projectName: manifestRead.manifest.project,
|
|
549
|
+
redactionProfile: manifestRead.manifest.redactionProfile,
|
|
550
|
+
traceCount: runs.length,
|
|
551
|
+
importedAt: options.importedAt
|
|
552
|
+
};
|
|
553
|
+
upsertStudioProject(options.db, row);
|
|
554
|
+
replaceProjectRuns(
|
|
555
|
+
options.db,
|
|
556
|
+
options.project.id,
|
|
557
|
+
runs.map((run) => ({ ...run, projectId: options.project.id }))
|
|
558
|
+
);
|
|
559
|
+
return { ...row, suiteConfigPaths };
|
|
560
|
+
}
|
|
561
|
+
async function resolveStudioRegistryPath(options) {
|
|
562
|
+
if (options.workspacePath && options.workspacePath.trim() !== "") {
|
|
563
|
+
return path10.resolve(options.cwd ?? process.cwd(), options.workspacePath);
|
|
564
|
+
}
|
|
565
|
+
const cwd = path10.resolve(options.cwd ?? process.cwd());
|
|
566
|
+
for (const rel of STUDIO_REGISTRY_FILENAMES) {
|
|
567
|
+
const candidate = path10.join(cwd, rel);
|
|
568
|
+
try {
|
|
569
|
+
await access(candidate);
|
|
570
|
+
return candidate;
|
|
571
|
+
} catch {
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
return path10.join(cwd, STUDIO_REGISTRY_FILENAMES[0]);
|
|
575
|
+
}
|
|
576
|
+
function resolveImportDirs(registryPath, registry) {
|
|
577
|
+
const registryDir = path10.dirname(registryPath);
|
|
578
|
+
const importConfig = registry.import ?? {};
|
|
579
|
+
const fileDropDir = importConfig.fileDropDir ?? "imports/drop";
|
|
580
|
+
const ciArtifactsDir = importConfig.ciArtifactsDir ?? "imports/ci";
|
|
581
|
+
const bundlesDir = importConfig.bundlesDir ?? "imports/bundles";
|
|
582
|
+
return {
|
|
583
|
+
registryDir,
|
|
584
|
+
fileDropDir: resolveUnderRoot(registryDir, fileDropDir),
|
|
585
|
+
ciArtifactsDir: resolveUnderRoot(registryDir, ciArtifactsDir),
|
|
586
|
+
bundlesDir: resolveUnderRoot(registryDir, bundlesDir)
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
function uniqueDestPath(destDir, fileName, contentHash) {
|
|
590
|
+
const ext = path10.extname(fileName);
|
|
591
|
+
const base = path10.basename(fileName, ext);
|
|
592
|
+
const shortHash = contentHash.slice(0, 8);
|
|
593
|
+
return path10.join(destDir, `${base}-${shortHash}${ext}`);
|
|
594
|
+
}
|
|
595
|
+
function sanitizeSafeErrorMessage(message, secret) {
|
|
596
|
+
if (!secret || secret.length < 4) return message;
|
|
597
|
+
return message.split(secret).join("[redacted]");
|
|
598
|
+
}
|
|
599
|
+
function parseGitHubRepo(repo) {
|
|
600
|
+
const trimmed = repo.trim();
|
|
601
|
+
const match = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/.exec(trimmed);
|
|
602
|
+
if (!match) {
|
|
603
|
+
throw new Error("repo must be in owner/name format");
|
|
604
|
+
}
|
|
605
|
+
return { owner: match[1], name: match[2] };
|
|
606
|
+
}
|
|
607
|
+
function buildGitHubArtifactSourceKey(options) {
|
|
608
|
+
return `github:${options.owner}/${options.repo}/runs/${options.runId}/${options.artifactName}`;
|
|
609
|
+
}
|
|
610
|
+
var DEFAULT_MAX_INGEST_BYTES = 52428800;
|
|
611
|
+
var IngestLimitError = class extends Error {
|
|
612
|
+
code;
|
|
613
|
+
constructor(code, message) {
|
|
614
|
+
super(message);
|
|
615
|
+
this.name = "IngestLimitError";
|
|
616
|
+
this.code = code;
|
|
617
|
+
}
|
|
618
|
+
};
|
|
619
|
+
function resolveIngestMaxBytes(configured) {
|
|
620
|
+
if (configured === void 0) return DEFAULT_MAX_INGEST_BYTES;
|
|
621
|
+
if (!Number.isInteger(configured) || configured <= 0) {
|
|
622
|
+
throw new IngestLimitError(
|
|
623
|
+
"INGEST_SIZE_LIMIT",
|
|
624
|
+
"maxBytes must be a positive integer"
|
|
625
|
+
);
|
|
626
|
+
}
|
|
627
|
+
return configured;
|
|
628
|
+
}
|
|
629
|
+
async function lstatRegularFile(filePath) {
|
|
630
|
+
const info = await lstat(filePath);
|
|
631
|
+
if (info.isSymbolicLink()) {
|
|
632
|
+
throw new IngestLimitError(
|
|
633
|
+
"INGEST_SYMLINK_REJECTED",
|
|
634
|
+
"symbolic links are not allowed for ingest"
|
|
635
|
+
);
|
|
636
|
+
}
|
|
637
|
+
if (!info.isFile()) {
|
|
638
|
+
throw new IngestLimitError("INGEST_NOT_A_FILE", "ingest path must be a regular file");
|
|
639
|
+
}
|
|
640
|
+
return info;
|
|
641
|
+
}
|
|
642
|
+
async function lstatRegularDirectory(dirPath) {
|
|
643
|
+
const info = await lstat(dirPath);
|
|
644
|
+
if (info.isSymbolicLink()) {
|
|
645
|
+
throw new IngestLimitError(
|
|
646
|
+
"INGEST_SYMLINK_REJECTED",
|
|
647
|
+
"symbolic links are not allowed for ingest"
|
|
648
|
+
);
|
|
649
|
+
}
|
|
650
|
+
if (!info.isDirectory()) {
|
|
651
|
+
throw new IngestLimitError(
|
|
652
|
+
"INGEST_NOT_A_DIRECTORY",
|
|
653
|
+
"ingest path must be a directory"
|
|
654
|
+
);
|
|
655
|
+
}
|
|
656
|
+
return info;
|
|
657
|
+
}
|
|
658
|
+
async function assertFileWithinByteLimit(filePath, maxBytes) {
|
|
659
|
+
const info = await lstatRegularFile(filePath);
|
|
660
|
+
if (info.size > maxBytes) {
|
|
661
|
+
throw new IngestLimitError("INGEST_SIZE_LIMIT", "file exceeds size limit");
|
|
662
|
+
}
|
|
663
|
+
return info;
|
|
664
|
+
}
|
|
665
|
+
async function measureDirectoryBytes(dirPath, maxBytes) {
|
|
666
|
+
await lstatRegularDirectory(dirPath);
|
|
667
|
+
let total = 0;
|
|
668
|
+
const walk = async (current) => {
|
|
669
|
+
const entries = await readdir(current, { withFileTypes: true });
|
|
670
|
+
for (const entry of entries) {
|
|
671
|
+
const abs = path10.join(current, entry.name);
|
|
672
|
+
const info = await lstat(abs);
|
|
673
|
+
if (info.isSymbolicLink()) {
|
|
674
|
+
throw new IngestLimitError(
|
|
675
|
+
"INGEST_SYMLINK_REJECTED",
|
|
676
|
+
"symbolic links are not allowed for ingest"
|
|
677
|
+
);
|
|
678
|
+
}
|
|
679
|
+
if (info.isDirectory()) {
|
|
680
|
+
await walk(abs);
|
|
681
|
+
continue;
|
|
682
|
+
}
|
|
683
|
+
if (!info.isFile()) continue;
|
|
684
|
+
total += info.size;
|
|
685
|
+
if (total > maxBytes) {
|
|
686
|
+
throw new IngestLimitError("INGEST_SIZE_LIMIT", "directory exceeds size limit");
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
await walk(dirPath);
|
|
691
|
+
return total;
|
|
692
|
+
}
|
|
693
|
+
async function readBoundedResponseBody(response, maxBytes) {
|
|
694
|
+
const lengthHeader = response.headers.get("content-length");
|
|
695
|
+
if (lengthHeader) {
|
|
696
|
+
const length = Number(lengthHeader);
|
|
697
|
+
if (Number.isFinite(length) && length > maxBytes) {
|
|
698
|
+
throw new IngestLimitError("INGEST_SIZE_LIMIT", "response exceeds size limit");
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
if (!response.body) {
|
|
702
|
+
const arrayBuffer = await response.arrayBuffer();
|
|
703
|
+
if (arrayBuffer.byteLength > maxBytes) {
|
|
704
|
+
throw new IngestLimitError("INGEST_SIZE_LIMIT", "response exceeds size limit");
|
|
705
|
+
}
|
|
706
|
+
return Buffer.from(arrayBuffer);
|
|
707
|
+
}
|
|
708
|
+
const reader = response.body.getReader();
|
|
709
|
+
const chunks = [];
|
|
710
|
+
let total = 0;
|
|
711
|
+
for (; ; ) {
|
|
712
|
+
const { done, value } = await reader.read();
|
|
713
|
+
if (done) break;
|
|
714
|
+
if (!value || value.byteLength === 0) continue;
|
|
715
|
+
total += value.byteLength;
|
|
716
|
+
if (total > maxBytes) {
|
|
717
|
+
try {
|
|
718
|
+
await reader.cancel();
|
|
719
|
+
} catch {
|
|
720
|
+
}
|
|
721
|
+
throw new IngestLimitError("INGEST_SIZE_LIMIT", "response exceeds size limit");
|
|
722
|
+
}
|
|
723
|
+
chunks.push(Buffer.from(value));
|
|
724
|
+
}
|
|
725
|
+
return Buffer.concat(chunks);
|
|
726
|
+
}
|
|
727
|
+
async function withAtomicStagingDir(parentDir, work) {
|
|
728
|
+
await mkdir(parentDir, { recursive: true });
|
|
729
|
+
const stagingDir = await mkdtemp(path10.join(parentDir, ".ingest-staging-"));
|
|
730
|
+
try {
|
|
731
|
+
return await work(stagingDir);
|
|
732
|
+
} finally {
|
|
733
|
+
await rm(stagingDir, { recursive: true, force: true });
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
async function promoteStagingPath(stagingPath, finalPath) {
|
|
737
|
+
await mkdir(path10.dirname(finalPath), { recursive: true });
|
|
738
|
+
await rename(stagingPath, finalPath);
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
// packages/studio/src/ingest/file-drop.ts
|
|
742
|
+
var FILE_DROP_ARCHIVE_DIR = ".imported";
|
|
743
|
+
var CI_EXTENSIONS = [".jsonl", ".suite.json"];
|
|
744
|
+
var BUNDLE_EXTENSIONS = [".tgz", ".zip"];
|
|
745
|
+
function classifyFile(fileName) {
|
|
746
|
+
const lower = fileName.toLowerCase();
|
|
747
|
+
if (CI_EXTENSIONS.some((ext) => lower.endsWith(ext))) return "ci";
|
|
748
|
+
if (BUNDLE_EXTENSIONS.some((ext) => lower.endsWith(ext))) return "bundle";
|
|
749
|
+
return void 0;
|
|
750
|
+
}
|
|
751
|
+
async function hashFile(filePath) {
|
|
752
|
+
const hash = createHash("sha256");
|
|
753
|
+
const stream = createReadStream(filePath);
|
|
754
|
+
for await (const chunk of stream) {
|
|
755
|
+
hash.update(chunk);
|
|
756
|
+
}
|
|
757
|
+
return hash.digest("hex");
|
|
758
|
+
}
|
|
759
|
+
async function importOneFile(options) {
|
|
760
|
+
const destPath = uniqueDestPath(options.destDir, options.fileName, options.contentHash);
|
|
761
|
+
assertPathUnderRoot(destPath, path10.dirname(options.destDir));
|
|
762
|
+
try {
|
|
763
|
+
await withAtomicStagingDir(options.destDir, async (stagingDir) => {
|
|
764
|
+
const stagedPath = path10.join(stagingDir, options.fileName);
|
|
765
|
+
await copyFile(options.sourcePath, stagedPath);
|
|
766
|
+
await promoteStagingPath(stagedPath, destPath);
|
|
767
|
+
});
|
|
768
|
+
insertIngestFile(options.db, {
|
|
769
|
+
sourceKey: options.sourceKey,
|
|
770
|
+
sourceName: options.fileName,
|
|
771
|
+
destPath,
|
|
772
|
+
kind: options.kind,
|
|
773
|
+
contentHash: options.contentHash,
|
|
774
|
+
importedAt: options.importedAt
|
|
775
|
+
});
|
|
776
|
+
} catch (error) {
|
|
777
|
+
await rm(destPath, { force: true }).catch(() => void 0);
|
|
778
|
+
throw error;
|
|
779
|
+
}
|
|
780
|
+
let archived = false;
|
|
781
|
+
if (options.archiveAfterImport) {
|
|
782
|
+
await mkdir(options.archiveDir, { recursive: true });
|
|
783
|
+
const archiveTarget = path10.join(options.archiveDir, options.fileName);
|
|
784
|
+
await rename(options.sourcePath, archiveTarget);
|
|
785
|
+
archived = true;
|
|
786
|
+
}
|
|
787
|
+
return {
|
|
788
|
+
sourceKey: options.sourceKey,
|
|
789
|
+
sourceName: options.fileName,
|
|
790
|
+
destPath,
|
|
791
|
+
kind: options.kind,
|
|
792
|
+
contentHash: options.contentHash,
|
|
793
|
+
archived
|
|
794
|
+
};
|
|
795
|
+
}
|
|
796
|
+
async function importFileDrop(options) {
|
|
797
|
+
const warnings = [];
|
|
798
|
+
const errors = [];
|
|
799
|
+
const files = [];
|
|
800
|
+
if (!options.enabled) {
|
|
801
|
+
return {
|
|
802
|
+
skipped: true,
|
|
803
|
+
reason: "file-drop ingest is disabled; pass --ingest file-drop or use studio import drop",
|
|
804
|
+
scanned: 0,
|
|
805
|
+
imported: 0,
|
|
806
|
+
skippedFiles: 0,
|
|
807
|
+
errors,
|
|
808
|
+
warnings,
|
|
809
|
+
files
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
let maxBytes;
|
|
813
|
+
try {
|
|
814
|
+
maxBytes = resolveIngestMaxBytes(
|
|
815
|
+
options.maxBytes ?? options.registry.ingest?.fileDrop?.maxBytes
|
|
816
|
+
);
|
|
817
|
+
} catch (error) {
|
|
818
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
819
|
+
return {
|
|
820
|
+
skipped: false,
|
|
821
|
+
scanned: 0,
|
|
822
|
+
imported: 0,
|
|
823
|
+
skippedFiles: 0,
|
|
824
|
+
errors: [message],
|
|
825
|
+
warnings,
|
|
826
|
+
files
|
|
827
|
+
};
|
|
828
|
+
}
|
|
829
|
+
const dirs = resolveImportDirs(options.registryPath, options.registry);
|
|
830
|
+
let dropDir;
|
|
831
|
+
try {
|
|
832
|
+
dropDir = options.dropDir ? path10.isAbsolute(options.dropDir) ? (assertPathUnderRoot(options.dropDir, dirs.registryDir), options.dropDir) : resolveUnderRoot(dirs.registryDir, options.dropDir) : dirs.fileDropDir;
|
|
833
|
+
assertPathUnderRoot(dropDir, dirs.registryDir);
|
|
834
|
+
} catch (error) {
|
|
835
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
836
|
+
return {
|
|
837
|
+
skipped: false,
|
|
838
|
+
scanned: 0,
|
|
839
|
+
imported: 0,
|
|
840
|
+
skippedFiles: 0,
|
|
841
|
+
errors: [message],
|
|
842
|
+
warnings,
|
|
843
|
+
files
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
let entries;
|
|
847
|
+
try {
|
|
848
|
+
entries = await readdir(dropDir);
|
|
849
|
+
} catch (error) {
|
|
850
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
851
|
+
return {
|
|
852
|
+
skipped: false,
|
|
853
|
+
scanned: 0,
|
|
854
|
+
imported: 0,
|
|
855
|
+
skippedFiles: 0,
|
|
856
|
+
errors: [`unable to read file-drop directory: ${message}`],
|
|
857
|
+
warnings,
|
|
858
|
+
files
|
|
859
|
+
};
|
|
860
|
+
}
|
|
861
|
+
const importedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
862
|
+
const archiveDir = path10.join(dropDir, FILE_DROP_ARCHIVE_DIR);
|
|
863
|
+
let scanned = 0;
|
|
864
|
+
let imported = 0;
|
|
865
|
+
let skippedFiles = 0;
|
|
866
|
+
for (const entry of entries.sort()) {
|
|
867
|
+
if (entry === FILE_DROP_ARCHIVE_DIR || entry.startsWith(".")) continue;
|
|
868
|
+
const sourcePath = path10.join(dropDir, entry);
|
|
869
|
+
const kind = classifyFile(entry);
|
|
870
|
+
if (!kind) continue;
|
|
871
|
+
scanned += 1;
|
|
872
|
+
try {
|
|
873
|
+
await assertFileWithinByteLimit(sourcePath, maxBytes);
|
|
874
|
+
} catch (error) {
|
|
875
|
+
if (error instanceof IngestLimitError && error.code === "INGEST_NOT_A_FILE") {
|
|
876
|
+
scanned -= 1;
|
|
877
|
+
continue;
|
|
878
|
+
}
|
|
879
|
+
if (error instanceof IngestLimitError && error.code === "INGEST_SYMLINK_REJECTED") {
|
|
880
|
+
errors.push(`failed to import ${entry}: ${error.message}`);
|
|
881
|
+
continue;
|
|
882
|
+
}
|
|
883
|
+
if (error instanceof IngestLimitError && error.code === "INGEST_SIZE_LIMIT") {
|
|
884
|
+
errors.push(`failed to import ${entry}: ${error.message}`);
|
|
885
|
+
continue;
|
|
886
|
+
}
|
|
887
|
+
warnings.push(`skipped unreadable entry: ${entry}`);
|
|
888
|
+
scanned -= 1;
|
|
889
|
+
continue;
|
|
890
|
+
}
|
|
891
|
+
const sourceKey = entry;
|
|
892
|
+
let contentHash;
|
|
893
|
+
try {
|
|
894
|
+
contentHash = await hashFile(sourcePath);
|
|
895
|
+
} catch (error) {
|
|
896
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
897
|
+
errors.push(`failed to read ${entry}: ${message}`);
|
|
898
|
+
continue;
|
|
899
|
+
}
|
|
900
|
+
const existing = findIngestFileBySourceKey(options.db, sourceKey);
|
|
901
|
+
if (existing && existing.contentHash === contentHash) {
|
|
902
|
+
skippedFiles += 1;
|
|
903
|
+
continue;
|
|
904
|
+
}
|
|
905
|
+
const destDir = kind === "ci" ? dirs.ciArtifactsDir : dirs.bundlesDir;
|
|
906
|
+
try {
|
|
907
|
+
const importedFile = await importOneFile({
|
|
908
|
+
db: options.db,
|
|
909
|
+
sourcePath,
|
|
910
|
+
sourceKey,
|
|
911
|
+
fileName: entry,
|
|
912
|
+
kind,
|
|
913
|
+
destDir,
|
|
914
|
+
archiveAfterImport: options.archiveAfterImport === true,
|
|
915
|
+
archiveDir,
|
|
916
|
+
importedAt,
|
|
917
|
+
contentHash
|
|
918
|
+
});
|
|
919
|
+
files.push(importedFile);
|
|
920
|
+
imported += 1;
|
|
921
|
+
} catch (error) {
|
|
922
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
923
|
+
errors.push(`failed to import ${entry}: ${message}`);
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
return {
|
|
927
|
+
skipped: false,
|
|
928
|
+
scanned,
|
|
929
|
+
imported,
|
|
930
|
+
skippedFiles,
|
|
931
|
+
errors,
|
|
932
|
+
warnings,
|
|
933
|
+
files
|
|
934
|
+
};
|
|
935
|
+
}
|
|
936
|
+
async function importFileDropFromRegistry(options) {
|
|
937
|
+
return importFileDrop({
|
|
938
|
+
db: options.db,
|
|
939
|
+
registryPath: options.registryPath,
|
|
940
|
+
registry: options.registry,
|
|
941
|
+
enabled: options.enabled,
|
|
942
|
+
...options.dropDir !== void 0 ? { dropDir: options.dropDir } : {},
|
|
943
|
+
...options.archiveAfterImport !== void 0 ? { archiveAfterImport: options.archiveAfterImport } : {},
|
|
944
|
+
...options.maxBytes !== void 0 ? { maxBytes: options.maxBytes } : {}
|
|
945
|
+
});
|
|
946
|
+
}
|
|
947
|
+
async function runStudioFileDropImport(options) {
|
|
948
|
+
const cwd = options.cwd ?? process.cwd();
|
|
949
|
+
const registryPath = await resolveStudioRegistryPath({
|
|
950
|
+
...options.workspacePath !== void 0 ? { workspacePath: options.workspacePath } : {},
|
|
951
|
+
cwd
|
|
952
|
+
});
|
|
953
|
+
const registryRead = await readStudioRegistryFile(registryPath);
|
|
954
|
+
if (!registryRead.ok || registryRead.registry === void 0) {
|
|
955
|
+
throw new Error(registryRead.errors.join("; ") || "invalid studio registry");
|
|
956
|
+
}
|
|
957
|
+
const dbPath = resolveStudioDbPath({
|
|
958
|
+
...options.dbPath !== void 0 ? { dbPath: options.dbPath } : {},
|
|
959
|
+
cwd
|
|
960
|
+
});
|
|
961
|
+
const db = openStudioDb(dbPath);
|
|
962
|
+
return importFileDropFromRegistry({
|
|
963
|
+
db,
|
|
964
|
+
registryPath,
|
|
965
|
+
registry: registryRead.registry,
|
|
966
|
+
enabled: true,
|
|
967
|
+
...options.dropDir !== void 0 ? { dropDir: options.dropDir } : {},
|
|
968
|
+
...options.archiveAfterImport !== void 0 ? { archiveAfterImport: options.archiveAfterImport } : {}
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
// packages/studio/src/context.ts
|
|
973
|
+
async function createStudioContext(options = {}) {
|
|
974
|
+
const cwd = options.cwd ?? process.cwd();
|
|
975
|
+
const registryPath = await resolveStudioRegistryPath({
|
|
976
|
+
...options.workspacePath !== void 0 ? { workspacePath: options.workspacePath } : {},
|
|
977
|
+
cwd
|
|
978
|
+
});
|
|
979
|
+
const registryRead = await readStudioRegistryFile(registryPath);
|
|
980
|
+
if (!registryRead.ok || registryRead.registry === void 0) {
|
|
981
|
+
throw new Error(registryRead.errors.join("; ") || "invalid studio registry");
|
|
982
|
+
}
|
|
983
|
+
const dbPath = resolveStudioDbPath({
|
|
984
|
+
...options.dbPath !== void 0 ? { dbPath: options.dbPath } : {},
|
|
985
|
+
cwd
|
|
986
|
+
});
|
|
987
|
+
const db = openStudioDb(dbPath);
|
|
988
|
+
const importResult = await importStudioRegistry({
|
|
989
|
+
db,
|
|
990
|
+
registry: registryRead.registry,
|
|
991
|
+
registryPath
|
|
992
|
+
});
|
|
993
|
+
let fileDropResult;
|
|
994
|
+
if (options.ingestFileDrop === true) {
|
|
995
|
+
fileDropResult = await importFileDropFromRegistry({
|
|
996
|
+
db,
|
|
997
|
+
registryPath,
|
|
998
|
+
registry: registryRead.registry,
|
|
999
|
+
enabled: true,
|
|
1000
|
+
...options.archiveFileDrop === true ? { archiveAfterImport: true } : {}
|
|
1001
|
+
});
|
|
1002
|
+
}
|
|
1003
|
+
return {
|
|
1004
|
+
db,
|
|
1005
|
+
dbPath,
|
|
1006
|
+
registryPath,
|
|
1007
|
+
registry: registryRead.registry,
|
|
1008
|
+
importResult,
|
|
1009
|
+
...fileDropResult !== void 0 ? { fileDropResult } : {},
|
|
1010
|
+
projects: importResult.projects
|
|
1011
|
+
};
|
|
1012
|
+
}
|
|
1013
|
+
function summarizeProjects(projects) {
|
|
1014
|
+
return projects.map((project) => ({
|
|
1015
|
+
id: project.id,
|
|
1016
|
+
label: project.label ?? project.id,
|
|
1017
|
+
projectName: project.projectName,
|
|
1018
|
+
traceCount: project.traceCount,
|
|
1019
|
+
redactionProfile: project.redactionProfile,
|
|
1020
|
+
importedAt: project.importedAt
|
|
1021
|
+
}));
|
|
1022
|
+
}
|
|
1023
|
+
var DEFAULT_INGEST_TOKEN_ENV = "STUDIO_INGEST_TOKEN";
|
|
1024
|
+
function resolveIngestTokenEnv(options) {
|
|
1025
|
+
const envName = options.tokenEnv?.trim() || options.registryTokenEnv?.trim() || DEFAULT_INGEST_TOKEN_ENV;
|
|
1026
|
+
if (!/^[A-Z][A-Z0-9_]*$/.test(envName)) {
|
|
1027
|
+
throw new Error("ingest token env name must be an uppercase identifier");
|
|
1028
|
+
}
|
|
1029
|
+
return envName;
|
|
1030
|
+
}
|
|
1031
|
+
function resolveIngestToken(envName) {
|
|
1032
|
+
const token = process.env[envName]?.trim();
|
|
1033
|
+
return token && token.length > 0 ? token : void 0;
|
|
1034
|
+
}
|
|
1035
|
+
function extractIngestTokenFromRequest(headers) {
|
|
1036
|
+
const headerToken = firstHeader(headers["x-agentinspect-token"]) ?? firstHeader(headers["x-agent-inspect-token"]);
|
|
1037
|
+
if (headerToken) return headerToken;
|
|
1038
|
+
const auth = firstHeader(headers.authorization);
|
|
1039
|
+
if (auth?.startsWith("Bearer ")) {
|
|
1040
|
+
const token = auth.slice("Bearer ".length).trim();
|
|
1041
|
+
return token.length > 0 ? token : void 0;
|
|
1042
|
+
}
|
|
1043
|
+
return void 0;
|
|
1044
|
+
}
|
|
1045
|
+
function firstHeader(value) {
|
|
1046
|
+
if (Array.isArray(value)) return value[0]?.trim();
|
|
1047
|
+
return value?.trim();
|
|
1048
|
+
}
|
|
1049
|
+
function isIngestTokenValid(provided, expected) {
|
|
1050
|
+
if (!provided || !expected) return false;
|
|
1051
|
+
const providedBuf = Buffer.from(provided);
|
|
1052
|
+
const expectedBuf = Buffer.from(expected);
|
|
1053
|
+
if (providedBuf.length !== expectedBuf.length) return false;
|
|
1054
|
+
return timingSafeEqual(providedBuf, expectedBuf);
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
// packages/studio/src/ingest/http.ts
|
|
1058
|
+
var DEFAULT_HTTP_INGEST_BASE_PATH = "/api/ingest";
|
|
1059
|
+
var HTTP_INGEST_BUNDLE_PATH = "/api/ingest/bundle";
|
|
1060
|
+
var HTTP_INGEST_ARTIFACT_PATH = "/api/ingest/artifact";
|
|
1061
|
+
function resolveHttpIngestConfig(options, registryHttp) {
|
|
1062
|
+
const http = registryHttp ?? options.context?.registry.ingest?.http;
|
|
1063
|
+
const enabled = options.ingestHttp === true || http?.enabled === true;
|
|
1064
|
+
const basePath = (http?.path ?? DEFAULT_HTTP_INGEST_BASE_PATH).trim() || DEFAULT_HTTP_INGEST_BASE_PATH;
|
|
1065
|
+
const tokenEnv = resolveIngestTokenEnv({
|
|
1066
|
+
...options.ingestTokenEnv !== void 0 ? { tokenEnv: options.ingestTokenEnv } : {},
|
|
1067
|
+
...http?.tokenEnv !== void 0 ? { registryTokenEnv: http.tokenEnv } : {}
|
|
1068
|
+
});
|
|
1069
|
+
const maxBytes = resolveIngestMaxBytes(http?.maxBytes);
|
|
1070
|
+
return { enabled, basePath, tokenEnv, maxBytes };
|
|
1071
|
+
}
|
|
1072
|
+
function sendJson(res, status, body) {
|
|
1073
|
+
res.writeHead(status, {
|
|
1074
|
+
"content-type": "application/json; charset=utf-8",
|
|
1075
|
+
"cache-control": "no-store"
|
|
1076
|
+
});
|
|
1077
|
+
res.end(JSON.stringify(body));
|
|
1078
|
+
}
|
|
1079
|
+
async function readBoundedRequestBody(req, maxBytes) {
|
|
1080
|
+
const chunks = [];
|
|
1081
|
+
let total = 0;
|
|
1082
|
+
for await (const chunk of req) {
|
|
1083
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
1084
|
+
total += buf.length;
|
|
1085
|
+
if (total > maxBytes) {
|
|
1086
|
+
throw new Error("request body exceeds size limit");
|
|
1087
|
+
}
|
|
1088
|
+
chunks.push(buf);
|
|
1089
|
+
}
|
|
1090
|
+
return Buffer.concat(chunks);
|
|
1091
|
+
}
|
|
1092
|
+
function isHttpIngestRoute(pathname, config) {
|
|
1093
|
+
return pathname === HTTP_INGEST_BUNDLE_PATH || pathname === HTTP_INGEST_ARTIFACT_PATH || pathname === `${config.basePath}/bundle` || pathname === `${config.basePath}/artifact`;
|
|
1094
|
+
}
|
|
1095
|
+
async function handleHttpIngestRequest(req, res, ctx, options, pathname) {
|
|
1096
|
+
const config = resolveHttpIngestConfig(options, ctx.registry.ingest?.http);
|
|
1097
|
+
if (!isHttpIngestRoute(pathname, config)) return false;
|
|
1098
|
+
if (!config.enabled) {
|
|
1099
|
+
sendJson(res, 404, { error: "HTTP ingest is disabled" });
|
|
1100
|
+
return true;
|
|
1101
|
+
}
|
|
1102
|
+
if (req.method !== "POST") {
|
|
1103
|
+
sendJson(res, 405, { error: "Method not allowed" });
|
|
1104
|
+
return true;
|
|
1105
|
+
}
|
|
1106
|
+
const expectedToken = resolveIngestToken(config.tokenEnv);
|
|
1107
|
+
const providedToken = extractIngestTokenFromRequest(req.headers);
|
|
1108
|
+
if (!isIngestTokenValid(providedToken, expectedToken)) {
|
|
1109
|
+
sendJson(res, 403, { error: "Invalid or missing ingest token" });
|
|
1110
|
+
return true;
|
|
1111
|
+
}
|
|
1112
|
+
let body;
|
|
1113
|
+
try {
|
|
1114
|
+
body = await readBoundedRequestBody(req, config.maxBytes);
|
|
1115
|
+
} catch (error) {
|
|
1116
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1117
|
+
const status = message.includes("size limit") ? 413 : 400;
|
|
1118
|
+
sendJson(res, status, { error: sanitizeSafeErrorMessage(message, expectedToken) });
|
|
1119
|
+
return true;
|
|
1120
|
+
}
|
|
1121
|
+
if (body.length === 0) {
|
|
1122
|
+
sendJson(res, 400, { error: "Empty request body" });
|
|
1123
|
+
return true;
|
|
1124
|
+
}
|
|
1125
|
+
try {
|
|
1126
|
+
const isBundle = pathname === HTTP_INGEST_BUNDLE_PATH || pathname === `${config.basePath}/bundle`;
|
|
1127
|
+
const isArtifact = pathname === HTTP_INGEST_ARTIFACT_PATH || pathname === `${config.basePath}/artifact`;
|
|
1128
|
+
if (!isBundle && !isArtifact) {
|
|
1129
|
+
sendJson(res, 404, { error: "Unknown ingest route" });
|
|
1130
|
+
return true;
|
|
1131
|
+
}
|
|
1132
|
+
const dirs = resolveImportDirs(ctx.registryPath, ctx.registry);
|
|
1133
|
+
const contentHash = createHash("sha256").update(body).digest("hex");
|
|
1134
|
+
const importedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1135
|
+
const fileName = isBundle ? `http-bundle-${contentHash.slice(0, 8)}.bin` : `http-artifact-${contentHash.slice(0, 8)}.zip`;
|
|
1136
|
+
const destDir = isBundle ? dirs.bundlesDir : dirs.ciArtifactsDir;
|
|
1137
|
+
const destPath = uniqueDestPath(destDir, fileName, contentHash);
|
|
1138
|
+
assertPathUnderRoot(destPath, dirs.registryDir);
|
|
1139
|
+
try {
|
|
1140
|
+
await withAtomicStagingDir(destDir, async (stagingDir) => {
|
|
1141
|
+
const stagedPath = path10.join(stagingDir, fileName);
|
|
1142
|
+
await writeFile(stagedPath, body);
|
|
1143
|
+
await promoteStagingPath(stagedPath, destPath);
|
|
1144
|
+
});
|
|
1145
|
+
const sourceKey = isBundle ? `http:bundle:${contentHash}` : buildGitHubArtifactSourceKey({
|
|
1146
|
+
owner: "http",
|
|
1147
|
+
repo: "ingest",
|
|
1148
|
+
runId: importedAt,
|
|
1149
|
+
artifactName: fileName
|
|
1150
|
+
});
|
|
1151
|
+
insertIngestFile(ctx.db, {
|
|
1152
|
+
sourceKey,
|
|
1153
|
+
sourceName: fileName,
|
|
1154
|
+
destPath,
|
|
1155
|
+
kind: isBundle ? "bundle" : "ci",
|
|
1156
|
+
contentHash,
|
|
1157
|
+
importedAt
|
|
1158
|
+
});
|
|
1159
|
+
} catch (error) {
|
|
1160
|
+
await rm(destPath, { force: true }).catch(() => void 0);
|
|
1161
|
+
throw error;
|
|
1162
|
+
}
|
|
1163
|
+
const registryImport = await importStudioRegistry({
|
|
1164
|
+
db: ctx.db,
|
|
1165
|
+
registry: ctx.registry,
|
|
1166
|
+
registryPath: ctx.registryPath
|
|
1167
|
+
});
|
|
1168
|
+
sendJson(res, 200, {
|
|
1169
|
+
ok: true,
|
|
1170
|
+
imported: true,
|
|
1171
|
+
kind: isBundle ? "bundle" : "artifact",
|
|
1172
|
+
destPath,
|
|
1173
|
+
warnings: registryImport.warnings
|
|
1174
|
+
});
|
|
1175
|
+
return true;
|
|
1176
|
+
} catch (error) {
|
|
1177
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1178
|
+
sendJson(res, 500, { error: sanitizeSafeErrorMessage(message, expectedToken) });
|
|
1179
|
+
return true;
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
// packages/studio/src/html.ts
|
|
1184
|
+
var studioIndexHtml = `<!DOCTYPE html>
|
|
1185
|
+
<html lang="en">
|
|
1186
|
+
<head>
|
|
1187
|
+
<meta charset="utf-8" />
|
|
1188
|
+
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'unsafe-inline'; script-src 'unsafe-inline'" />
|
|
1189
|
+
<title>AgentInspect Studio</title>
|
|
1190
|
+
<style>
|
|
1191
|
+
body { font-family: system-ui, sans-serif; margin: 0; line-height: 1.4; color: #111; }
|
|
1192
|
+
header { padding: 1rem 1.5rem; border-bottom: 1px solid #ddd; background: #fafafa; }
|
|
1193
|
+
nav a { margin-right: 1rem; color: #0b57d0; text-decoration: none; }
|
|
1194
|
+
nav a.active { font-weight: 600; text-decoration: underline; }
|
|
1195
|
+
main { padding: 1.5rem; max-width: 1100px; }
|
|
1196
|
+
.muted { color: #666; }
|
|
1197
|
+
table { border-collapse: collapse; width: 100%; margin: 1rem 0; }
|
|
1198
|
+
th, td { border: 1px solid #ddd; padding: 0.5rem; text-align: left; vertical-align: top; }
|
|
1199
|
+
th { background: #f6f6f6; }
|
|
1200
|
+
pre { background: #f4f4f5; padding: 1rem; overflow: auto; max-height: 60vh; }
|
|
1201
|
+
.error { color: #b42318; }
|
|
1202
|
+
</style>
|
|
1203
|
+
</head>
|
|
1204
|
+
<body>
|
|
1205
|
+
<header>
|
|
1206
|
+
<h1>AgentInspect Studio</h1>
|
|
1207
|
+
<p class="muted">Self-hosted, read-only. SQLite only. JSONL remains canonical.</p>
|
|
1208
|
+
<nav id="nav">
|
|
1209
|
+
<a href="#projects" data-page="projects">Projects</a>
|
|
1210
|
+
<a href="#runs" data-page="runs">Runs</a>
|
|
1211
|
+
<a href="#sessions" data-page="sessions">Sessions</a>
|
|
1212
|
+
<a href="#suites" data-page="suites">Suites</a>
|
|
1213
|
+
<a href="#safety" data-page="safety">Safety</a>
|
|
1214
|
+
<a href="#imports" data-page="imports">Imports</a>
|
|
1215
|
+
<a href="#search" data-page="search">Search</a>
|
|
1216
|
+
</nav>
|
|
1217
|
+
</header>
|
|
1218
|
+
<main id="content"><p class="muted">Loading\u2026</p></main>
|
|
1219
|
+
<script>
|
|
1220
|
+
function escapeHtml(value) {
|
|
1221
|
+
return String(value ?? "")
|
|
1222
|
+
.replaceAll("&", "&")
|
|
1223
|
+
.replaceAll("<", "<")
|
|
1224
|
+
.replaceAll(">", ">")
|
|
1225
|
+
.replaceAll('"', """)
|
|
1226
|
+
.replaceAll("'", "'");
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
let state = { projects: [], projectId: null };
|
|
1230
|
+
|
|
1231
|
+
async function api(path) {
|
|
1232
|
+
const res = await fetch(path);
|
|
1233
|
+
const data = await res.json();
|
|
1234
|
+
if (!res.ok) throw new Error(data.error || res.statusText);
|
|
1235
|
+
return data;
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
function setPage(page) {
|
|
1239
|
+
document.querySelectorAll("#nav a").forEach((a) => {
|
|
1240
|
+
a.classList.toggle("active", a.dataset.page === page);
|
|
1241
|
+
});
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
function renderProjects() {
|
|
1245
|
+
setPage("projects");
|
|
1246
|
+
const rows = state.projects.map((p) =>
|
|
1247
|
+
'<tr><td><a href="#runs" data-select-project="' + escapeHtml(p.id) + '">' +
|
|
1248
|
+
escapeHtml(p.label || p.id) + '</a></td><td>' + escapeHtml(p.traceCount) +
|
|
1249
|
+
'</td><td>' + escapeHtml(p.path) + '</td></tr>'
|
|
1250
|
+
).join("");
|
|
1251
|
+
document.getElementById("content").innerHTML =
|
|
1252
|
+
'<h2>Projects</h2><table><thead><tr><th>Project</th><th>Runs</th><th>Path</th></tr></thead><tbody>' +
|
|
1253
|
+
(rows || '<tr><td colspan="3">No projects imported</td></tr>') + '</tbody></table>';
|
|
1254
|
+
document.querySelectorAll("[data-select-project]").forEach((el) => {
|
|
1255
|
+
el.addEventListener("click", (ev) => {
|
|
1256
|
+
ev.preventDefault();
|
|
1257
|
+
state.projectId = el.getAttribute("data-select-project");
|
|
1258
|
+
location.hash = "runs";
|
|
1259
|
+
renderRuns();
|
|
1260
|
+
});
|
|
1261
|
+
});
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
async function renderRuns() {
|
|
1265
|
+
setPage("runs");
|
|
1266
|
+
if (!state.projectId && state.projects[0]) state.projectId = state.projects[0].id;
|
|
1267
|
+
if (!state.projectId) {
|
|
1268
|
+
document.getElementById("content").innerHTML = '<p>Select a project first.</p>';
|
|
1269
|
+
return;
|
|
1270
|
+
}
|
|
1271
|
+
const data = await api("/api/projects/" + encodeURIComponent(state.projectId) + "/runs");
|
|
1272
|
+
const rows = (data.runs || []).map((r) =>
|
|
1273
|
+
'<tr><td>' + escapeHtml(r.runId) + '</td><td>' + escapeHtml(r.status) +
|
|
1274
|
+
'</td><td>' + escapeHtml(r.name) + '</td><td>' + escapeHtml(r.durationMs) + '</td></tr>'
|
|
1275
|
+
).join("");
|
|
1276
|
+
document.getElementById("content").innerHTML =
|
|
1277
|
+
'<h2>Runs \u2014 ' + escapeHtml(state.projectId) + '</h2>' +
|
|
1278
|
+
'<table><thead><tr><th>Run ID</th><th>Status</th><th>Name</th><th>Duration ms</th></tr></thead><tbody>' +
|
|
1279
|
+
rows + '</tbody></table>';
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
async function renderSimple(title, path) {
|
|
1283
|
+
setPage(title.toLowerCase());
|
|
1284
|
+
if (!state.projectId && state.projects[0]) state.projectId = state.projects[0].id;
|
|
1285
|
+
const data = await api("/api/projects/" + encodeURIComponent(state.projectId) + "/" + path);
|
|
1286
|
+
document.getElementById("content").innerHTML =
|
|
1287
|
+
'<h2>' + escapeHtml(title) + '</h2><pre>' + escapeHtml(JSON.stringify(data, null, 2)) + '</pre>';
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
async function renderImports() {
|
|
1291
|
+
setPage("imports");
|
|
1292
|
+
const health = await api("/api/health");
|
|
1293
|
+
document.getElementById("content").innerHTML =
|
|
1294
|
+
'<h2>Imports</h2><p>Registry: ' + escapeHtml(health.registryName) + '</p>' +
|
|
1295
|
+
'<pre>' + escapeHtml(JSON.stringify(health.warnings || [], null, 2)) + '</pre>';
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
async function renderSearch() {
|
|
1299
|
+
setPage("search");
|
|
1300
|
+
if (!state.projectId && state.projects[0]) state.projectId = state.projects[0].id;
|
|
1301
|
+
document.getElementById("content").innerHTML =
|
|
1302
|
+
'<h2>Search</h2><p><input id="q" placeholder="run id or name" /> <button id="go">Search</button></p><pre id="out"></pre>';
|
|
1303
|
+
document.getElementById("go").onclick = async () => {
|
|
1304
|
+
const q = document.getElementById("q").value;
|
|
1305
|
+
const data = await api("/api/search?projectId=" + encodeURIComponent(state.projectId) + "&q=" + encodeURIComponent(q));
|
|
1306
|
+
document.getElementById("out").textContent = JSON.stringify(data, null, 2);
|
|
1307
|
+
};
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
async function boot() {
|
|
1311
|
+
const health = await api("/api/health");
|
|
1312
|
+
const projects = await api("/api/projects");
|
|
1313
|
+
state.projects = projects.projects || health.projects || [];
|
|
1314
|
+
const page = (location.hash || "#projects").slice(1);
|
|
1315
|
+
if (page === "runs") return renderRuns();
|
|
1316
|
+
if (page === "sessions") return renderSimple("Sessions", "sessions");
|
|
1317
|
+
if (page === "suites") return renderSimple("Suites", "suites");
|
|
1318
|
+
if (page === "safety") return renderSimple("Safety", "redaction");
|
|
1319
|
+
if (page === "imports") return renderImports();
|
|
1320
|
+
if (page === "search") return renderSearch();
|
|
1321
|
+
return renderProjects();
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
window.addEventListener("hashchange", () => boot().catch(showError));
|
|
1325
|
+
function showError(err) {
|
|
1326
|
+
document.getElementById("content").innerHTML = '<p class="error">' + escapeHtml(String(err)) + '</p>';
|
|
1327
|
+
}
|
|
1328
|
+
boot().catch(showError);
|
|
1329
|
+
</script>
|
|
1330
|
+
</body>
|
|
1331
|
+
</html>`;
|
|
1332
|
+
function getImportedProject(db, projects, projectId) {
|
|
1333
|
+
const cached2 = projects.find((item) => item.id === projectId);
|
|
1334
|
+
if (cached2) return { project: cached2 };
|
|
1335
|
+
const row = getStudioProject(db, projectId);
|
|
1336
|
+
if (!row) return void 0;
|
|
1337
|
+
return {
|
|
1338
|
+
project: {
|
|
1339
|
+
...row,
|
|
1340
|
+
suiteConfigPaths: []
|
|
1341
|
+
}
|
|
1342
|
+
};
|
|
1343
|
+
}
|
|
1344
|
+
async function loadTraceDirMetas(workspaceDir, traceDirs) {
|
|
1345
|
+
const metas = [];
|
|
1346
|
+
for (const rel of traceDirs) {
|
|
1347
|
+
const traceDir = resolveTraceDir({ dir: path10.join(workspaceDir, rel) });
|
|
1348
|
+
const td = new TraceDirectory({ dir: traceDir });
|
|
1349
|
+
const files = await td.list();
|
|
1350
|
+
const listed = await loadTraceMetadataList(
|
|
1351
|
+
traceDir,
|
|
1352
|
+
files,
|
|
1353
|
+
(fileName) => td.getPath(fileName)
|
|
1354
|
+
);
|
|
1355
|
+
metas.push(...listed);
|
|
1356
|
+
}
|
|
1357
|
+
return metas;
|
|
1358
|
+
}
|
|
1359
|
+
async function loadProjectRunsView(ctx, db, limit = 200) {
|
|
1360
|
+
return listProjectRuns(db, ctx.project.id, limit);
|
|
1361
|
+
}
|
|
1362
|
+
async function loadProjectSessionsView(ctx) {
|
|
1363
|
+
const location = resolveWorkspaceLocation(ctx.project.path);
|
|
1364
|
+
const manifestRead = await readWorkspaceManifestFile(location);
|
|
1365
|
+
const traceDirs = manifestRead.manifest?.traceDirs ?? ["runs"];
|
|
1366
|
+
const metas = await loadTraceDirMetas(ctx.project.workspaceDir, traceDirs);
|
|
1367
|
+
const runs = await loadSessionRunRecords(metas);
|
|
1368
|
+
return buildSessionIndex(runs, { correlateByGroupId: true });
|
|
1369
|
+
}
|
|
1370
|
+
async function loadProjectSuitesView(ctx) {
|
|
1371
|
+
const suites = [];
|
|
1372
|
+
for (const configPath of ctx.project.suiteConfigPaths) {
|
|
1373
|
+
try {
|
|
1374
|
+
const result = await runSuite({
|
|
1375
|
+
configPath,
|
|
1376
|
+
cwd: path10.dirname(configPath)
|
|
1377
|
+
});
|
|
1378
|
+
suites.push({
|
|
1379
|
+
suiteName: result.suiteName,
|
|
1380
|
+
configPath: result.configPath,
|
|
1381
|
+
ok: result.ok,
|
|
1382
|
+
status: result.status,
|
|
1383
|
+
summary: result.summary,
|
|
1384
|
+
cases: result.cases.map((item) => ({
|
|
1385
|
+
id: item.id,
|
|
1386
|
+
status: item.status,
|
|
1387
|
+
...item.runId !== void 0 ? { runId: item.runId } : {},
|
|
1388
|
+
...item.message !== void 0 ? { message: item.message } : {}
|
|
1389
|
+
}))
|
|
1390
|
+
});
|
|
1391
|
+
} catch (error) {
|
|
1392
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1393
|
+
suites.push({
|
|
1394
|
+
suiteName: path10.basename(configPath),
|
|
1395
|
+
configPath,
|
|
1396
|
+
ok: false,
|
|
1397
|
+
status: "error",
|
|
1398
|
+
summary: { total: 0, passed: 0, failed: 0, skipped: 0 },
|
|
1399
|
+
cases: [],
|
|
1400
|
+
error: message
|
|
1401
|
+
});
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
return { suites };
|
|
1405
|
+
}
|
|
1406
|
+
async function loadProjectChecksView(ctx) {
|
|
1407
|
+
const metas = await loadTraceDirMetas(ctx.project.workspaceDir, ["runs"]);
|
|
1408
|
+
const results = [];
|
|
1409
|
+
for (const meta of metas.slice(0, 20)) {
|
|
1410
|
+
try {
|
|
1411
|
+
const read = await openTrace({ type: "file", path: meta.filePath });
|
|
1412
|
+
const result = runTraceChecks(
|
|
1413
|
+
{ read },
|
|
1414
|
+
{ rules: [createRunStatusRule()], select: ["run.status"], runId: meta.runId }
|
|
1415
|
+
);
|
|
1416
|
+
results.push({
|
|
1417
|
+
runId: meta.runId,
|
|
1418
|
+
ok: result.ok,
|
|
1419
|
+
summary: result.summary
|
|
1420
|
+
});
|
|
1421
|
+
} catch (error) {
|
|
1422
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1423
|
+
results.push({ runId: meta.runId, ok: false, error: message });
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
return { checks: results };
|
|
1427
|
+
}
|
|
1428
|
+
async function loadProjectSearchView(ctx, db, params) {
|
|
1429
|
+
const q = params.get("q")?.trim() ?? "";
|
|
1430
|
+
if (q) {
|
|
1431
|
+
return {
|
|
1432
|
+
query: q,
|
|
1433
|
+
results: searchProjectRuns(
|
|
1434
|
+
db,
|
|
1435
|
+
ctx.project.id,
|
|
1436
|
+
q,
|
|
1437
|
+
Number(params.get("limit") ?? 50)
|
|
1438
|
+
)
|
|
1439
|
+
};
|
|
1440
|
+
}
|
|
1441
|
+
const metas = await loadTraceDirMetas(ctx.project.workspaceDir, ["runs"]);
|
|
1442
|
+
const traceDir = resolveTraceDir({
|
|
1443
|
+
dir: path10.join(ctx.project.workspaceDir, "runs")
|
|
1444
|
+
});
|
|
1445
|
+
const results = await searchTraces(metas, {
|
|
1446
|
+
traceDir,
|
|
1447
|
+
...params.get("status") ? { status: params.get("status") } : {},
|
|
1448
|
+
...params.get("name") ? { name: params.get("name") ?? void 0 } : {},
|
|
1449
|
+
...params.get("tool") ? { tool: params.get("tool") ?? void 0 } : {},
|
|
1450
|
+
limit: Number(params.get("limit") ?? 50)
|
|
1451
|
+
});
|
|
1452
|
+
return { query: q, results };
|
|
1453
|
+
}
|
|
1454
|
+
async function loadProjectDiffView(ctx, params) {
|
|
1455
|
+
const leftRunId = params.get("left");
|
|
1456
|
+
const rightRunId = params.get("right");
|
|
1457
|
+
if (!leftRunId || !rightRunId) {
|
|
1458
|
+
throw new Error("left and right run ids are required.");
|
|
1459
|
+
}
|
|
1460
|
+
const metas = await loadTraceDirMetas(ctx.project.workspaceDir, ["runs"]);
|
|
1461
|
+
const leftMeta = metas.find((item) => item.runId === leftRunId);
|
|
1462
|
+
const rightMeta = metas.find((item) => item.runId === rightRunId);
|
|
1463
|
+
if (!leftMeta || !rightMeta) {
|
|
1464
|
+
throw new Error("One or both runs were not found in the project workspace.");
|
|
1465
|
+
}
|
|
1466
|
+
const leftRead = await openTrace({ type: "file", path: leftMeta.filePath });
|
|
1467
|
+
const rightRead = await openTrace({ type: "file", path: rightMeta.filePath });
|
|
1468
|
+
const diff = diffRuns(
|
|
1469
|
+
manualTraceEventsToComparableRun(
|
|
1470
|
+
persistedInspectEventsToTraceEvents(leftRead.events)
|
|
1471
|
+
),
|
|
1472
|
+
manualTraceEventsToComparableRun(
|
|
1473
|
+
persistedInspectEventsToTraceEvents(rightRead.events)
|
|
1474
|
+
)
|
|
1475
|
+
);
|
|
1476
|
+
return {
|
|
1477
|
+
leftRunId,
|
|
1478
|
+
rightRunId,
|
|
1479
|
+
summary: diff.summary,
|
|
1480
|
+
differences: diff.differences.slice(0, 50).map((item) => ({
|
|
1481
|
+
kind: item.kind,
|
|
1482
|
+
message: item.message
|
|
1483
|
+
}))
|
|
1484
|
+
};
|
|
1485
|
+
}
|
|
1486
|
+
async function loadProjectReportsView(ctx) {
|
|
1487
|
+
const reportsDir = path10.join(ctx.project.workspaceDir, "reports");
|
|
1488
|
+
const reports = [];
|
|
1489
|
+
try {
|
|
1490
|
+
const files = await readdir(reportsDir);
|
|
1491
|
+
for (const file of files) {
|
|
1492
|
+
const filePath = path10.join(reportsDir, file);
|
|
1493
|
+
const info = await stat(filePath);
|
|
1494
|
+
if (!info.isFile()) continue;
|
|
1495
|
+
reports.push({ name: file, path: filePath, sizeBytes: info.size });
|
|
1496
|
+
}
|
|
1497
|
+
} catch {
|
|
1498
|
+
}
|
|
1499
|
+
return { reports: reports.sort((a, b) => a.name.localeCompare(b.name)) };
|
|
1500
|
+
}
|
|
1501
|
+
async function loadProjectObservationsView(ctx) {
|
|
1502
|
+
const metas = await loadTraceDirMetas(ctx.project.workspaceDir, ["runs"]);
|
|
1503
|
+
const observations = [];
|
|
1504
|
+
for (const meta of metas.slice(0, 20)) {
|
|
1505
|
+
try {
|
|
1506
|
+
const read = await openTrace({ type: "file", path: meta.filePath });
|
|
1507
|
+
const legacy = persistedInspectEventsToTraceEvents(read.events);
|
|
1508
|
+
observations.push({
|
|
1509
|
+
runId: meta.runId,
|
|
1510
|
+
items: extractOutcomesFromTraceEvents(legacy),
|
|
1511
|
+
timeline: buildRunTimeline(legacy, { focus: "all" }).entries.filter((entry) => entry.type === "tool").map((entry) => entry.name)
|
|
1512
|
+
});
|
|
1513
|
+
} catch {
|
|
1514
|
+
observations.push({ runId: meta.runId, items: [], timeline: [] });
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
return { observations };
|
|
1518
|
+
}
|
|
1519
|
+
async function loadProjectGuardrailsView(ctx) {
|
|
1520
|
+
return {
|
|
1521
|
+
guardrails: {
|
|
1522
|
+
message: "Guardrail evaluation is available via CLI (`agent-inspect scan`). Studio surfaces structural status only in v6.0.",
|
|
1523
|
+
redactionProfile: ctx.project.redactionProfile ?? "share",
|
|
1524
|
+
circuitWarnings: []
|
|
1525
|
+
}
|
|
1526
|
+
};
|
|
1527
|
+
}
|
|
1528
|
+
async function loadProjectRedactionView(ctx) {
|
|
1529
|
+
return {
|
|
1530
|
+
redaction: {
|
|
1531
|
+
profile: ctx.project.redactionProfile ?? "share",
|
|
1532
|
+
hint: "Structural share-safety posture from workspace.json \u2014 not certification.",
|
|
1533
|
+
bundleCommand: `npx agent-inspect bundle <runId> --profile ${ctx.project.redactionProfile ?? "share"}`
|
|
1534
|
+
}
|
|
1535
|
+
};
|
|
1536
|
+
}
|
|
1537
|
+
async function loadBundleExportView(ctx, params) {
|
|
1538
|
+
const runId = params.get("runId");
|
|
1539
|
+
if (!runId) {
|
|
1540
|
+
throw new Error("runId query parameter is required.");
|
|
1541
|
+
}
|
|
1542
|
+
return {
|
|
1543
|
+
projectId: ctx.project.id,
|
|
1544
|
+
runId,
|
|
1545
|
+
readOnly: true,
|
|
1546
|
+
redactionProfile: ctx.project.redactionProfile ?? "share",
|
|
1547
|
+
cliHint: `npx agent-inspect bundle ${runId} --profile ${ctx.project.redactionProfile ?? "share"} --dir ${path10.join(ctx.project.workspaceDir, "runs")}`,
|
|
1548
|
+
note: "Studio does not mutate traces or upload bundles. Run the CLI locally to assemble a share-safe bundle."
|
|
1549
|
+
};
|
|
1550
|
+
}
|
|
1551
|
+
function resolveStudioAuthMode(options) {
|
|
1552
|
+
return options.auth === "basic" ? "basic" : "none";
|
|
1553
|
+
}
|
|
1554
|
+
function resolveStudioPassword(options) {
|
|
1555
|
+
if (!options.passwordEnv) return void 0;
|
|
1556
|
+
const value = process.env[options.passwordEnv]?.trim();
|
|
1557
|
+
return value && value.length > 0 ? value : void 0;
|
|
1558
|
+
}
|
|
1559
|
+
function parseBasicAuth(header) {
|
|
1560
|
+
if (!header || !header.startsWith("Basic ")) return void 0;
|
|
1561
|
+
try {
|
|
1562
|
+
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
1563
|
+
const separator = decoded.indexOf(":");
|
|
1564
|
+
if (separator < 0) return void 0;
|
|
1565
|
+
return decoded.slice(separator + 1);
|
|
1566
|
+
} catch {
|
|
1567
|
+
return void 0;
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
function timingSafePasswordEqual(provided, expected) {
|
|
1571
|
+
const providedDigest = createHash("sha256").update(provided, "utf8").digest();
|
|
1572
|
+
const expectedDigest = createHash("sha256").update(expected, "utf8").digest();
|
|
1573
|
+
return timingSafeEqual(providedDigest, expectedDigest);
|
|
1574
|
+
}
|
|
1575
|
+
function isStudioRequestAuthorized(req, options) {
|
|
1576
|
+
const mode = resolveStudioAuthMode(options);
|
|
1577
|
+
if (mode === "none") return true;
|
|
1578
|
+
const expected = resolveStudioPassword(options);
|
|
1579
|
+
if (!expected) return false;
|
|
1580
|
+
const provided = parseBasicAuth(req.headers.authorization);
|
|
1581
|
+
if (provided === void 0) return false;
|
|
1582
|
+
return timingSafePasswordEqual(provided, expected);
|
|
1583
|
+
}
|
|
1584
|
+
function studioAuthRequiredResponse() {
|
|
1585
|
+
return {
|
|
1586
|
+
status: 401,
|
|
1587
|
+
body: { error: "Unauthorized" },
|
|
1588
|
+
headers: {
|
|
1589
|
+
"www-authenticate": 'Basic realm="AgentInspect Studio"'
|
|
1590
|
+
}
|
|
1591
|
+
};
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1594
|
+
// packages/studio/src/routes.ts
|
|
1595
|
+
function sendJson2(res, status, body, headers = {}) {
|
|
1596
|
+
const payload = JSON.stringify(body);
|
|
1597
|
+
res.writeHead(status, {
|
|
1598
|
+
"content-type": "application/json; charset=utf-8",
|
|
1599
|
+
"cache-control": "no-store",
|
|
1600
|
+
...headers
|
|
1601
|
+
});
|
|
1602
|
+
res.end(payload);
|
|
1603
|
+
}
|
|
1604
|
+
function notFound(res, message) {
|
|
1605
|
+
sendJson2(res, 404, { error: message });
|
|
1606
|
+
}
|
|
1607
|
+
function decodeSegment(segment) {
|
|
1608
|
+
if (!segment) return "";
|
|
1609
|
+
try {
|
|
1610
|
+
return decodeURIComponent(segment);
|
|
1611
|
+
} catch {
|
|
1612
|
+
return segment;
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
async function handleStudioRoute(req, res, ctx, options, pathname, url) {
|
|
1616
|
+
if (!isStudioRequestAuthorized(req, options)) {
|
|
1617
|
+
const auth = studioAuthRequiredResponse();
|
|
1618
|
+
sendJson2(res, auth.status, auth.body, auth.headers);
|
|
1619
|
+
return true;
|
|
1620
|
+
}
|
|
1621
|
+
if (pathname === "/api/health") {
|
|
1622
|
+
sendJson2(res, 200, {
|
|
1623
|
+
ok: true,
|
|
1624
|
+
readOnly: true,
|
|
1625
|
+
mode: "studio",
|
|
1626
|
+
registryName: ctx.registry.name,
|
|
1627
|
+
registryPath: ctx.registryPath,
|
|
1628
|
+
dbPath: ctx.dbPath,
|
|
1629
|
+
projects: summarizeProjects(ctx.projects),
|
|
1630
|
+
warnings: ctx.importResult.warnings
|
|
1631
|
+
});
|
|
1632
|
+
return true;
|
|
1633
|
+
}
|
|
1634
|
+
if (pathname === "/api/projects") {
|
|
1635
|
+
sendJson2(res, 200, {
|
|
1636
|
+
registryName: ctx.registry.name,
|
|
1637
|
+
projects: summarizeProjects(ctx.projects),
|
|
1638
|
+
warnings: ctx.importResult.warnings
|
|
1639
|
+
});
|
|
1640
|
+
return true;
|
|
1641
|
+
}
|
|
1642
|
+
const projectMatch = pathname.match(/^\/api\/projects\/([^/]+)(?:\/(.*))?$/);
|
|
1643
|
+
if (projectMatch) {
|
|
1644
|
+
const projectId = decodeSegment(projectMatch[1]);
|
|
1645
|
+
const subpath = projectMatch[2] ?? "";
|
|
1646
|
+
const projectCtx = getImportedProject(ctx.db, ctx.projects, projectId);
|
|
1647
|
+
if (!projectCtx) {
|
|
1648
|
+
notFound(res, `Project not found: ${projectId}`);
|
|
1649
|
+
return true;
|
|
1650
|
+
}
|
|
1651
|
+
if (subpath === "runs" || subpath === "") {
|
|
1652
|
+
sendJson2(res, 200, {
|
|
1653
|
+
projectId,
|
|
1654
|
+
runs: await loadProjectRunsView(projectCtx, ctx.db)
|
|
1655
|
+
});
|
|
1656
|
+
return true;
|
|
1657
|
+
}
|
|
1658
|
+
if (subpath === "sessions") {
|
|
1659
|
+
sendJson2(res, 200, {
|
|
1660
|
+
projectId,
|
|
1661
|
+
...await loadProjectSessionsView(projectCtx)
|
|
1662
|
+
});
|
|
1663
|
+
return true;
|
|
1664
|
+
}
|
|
1665
|
+
if (subpath === "suites") {
|
|
1666
|
+
sendJson2(res, 200, {
|
|
1667
|
+
projectId,
|
|
1668
|
+
...await loadProjectSuitesView(projectCtx)
|
|
1669
|
+
});
|
|
1670
|
+
return true;
|
|
1671
|
+
}
|
|
1672
|
+
if (subpath === "checks") {
|
|
1673
|
+
sendJson2(res, 200, {
|
|
1674
|
+
projectId,
|
|
1675
|
+
...await loadProjectChecksView(projectCtx)
|
|
1676
|
+
});
|
|
1677
|
+
return true;
|
|
1678
|
+
}
|
|
1679
|
+
if (subpath === "observations") {
|
|
1680
|
+
sendJson2(res, 200, {
|
|
1681
|
+
projectId,
|
|
1682
|
+
...await loadProjectObservationsView(projectCtx)
|
|
1683
|
+
});
|
|
1684
|
+
return true;
|
|
1685
|
+
}
|
|
1686
|
+
if (subpath === "guardrails") {
|
|
1687
|
+
sendJson2(res, 200, {
|
|
1688
|
+
projectId,
|
|
1689
|
+
...await loadProjectGuardrailsView(projectCtx)
|
|
1690
|
+
});
|
|
1691
|
+
return true;
|
|
1692
|
+
}
|
|
1693
|
+
if (subpath === "redaction") {
|
|
1694
|
+
sendJson2(res, 200, {
|
|
1695
|
+
projectId,
|
|
1696
|
+
...await loadProjectRedactionView(projectCtx)
|
|
1697
|
+
});
|
|
1698
|
+
return true;
|
|
1699
|
+
}
|
|
1700
|
+
if (subpath === "reports") {
|
|
1701
|
+
sendJson2(res, 200, {
|
|
1702
|
+
projectId,
|
|
1703
|
+
...await loadProjectReportsView(projectCtx)
|
|
1704
|
+
});
|
|
1705
|
+
return true;
|
|
1706
|
+
}
|
|
1707
|
+
notFound(res, `Unknown project route: /${subpath}`);
|
|
1708
|
+
return true;
|
|
1709
|
+
}
|
|
1710
|
+
if (pathname === "/api/search") {
|
|
1711
|
+
const projectId = url.searchParams.get("projectId");
|
|
1712
|
+
if (!projectId) {
|
|
1713
|
+
sendJson2(res, 400, { error: "projectId query parameter is required." });
|
|
1714
|
+
return true;
|
|
1715
|
+
}
|
|
1716
|
+
const projectCtx = getImportedProject(ctx.db, ctx.projects, projectId);
|
|
1717
|
+
if (!projectCtx) {
|
|
1718
|
+
notFound(res, `Project not found: ${projectId}`);
|
|
1719
|
+
return true;
|
|
1720
|
+
}
|
|
1721
|
+
sendJson2(res, 200, {
|
|
1722
|
+
projectId,
|
|
1723
|
+
...await loadProjectSearchView(projectCtx, ctx.db, url.searchParams)
|
|
1724
|
+
});
|
|
1725
|
+
return true;
|
|
1726
|
+
}
|
|
1727
|
+
if (pathname === "/api/diff") {
|
|
1728
|
+
const projectId = url.searchParams.get("projectId");
|
|
1729
|
+
if (!projectId) {
|
|
1730
|
+
sendJson2(res, 400, { error: "projectId query parameter is required." });
|
|
1731
|
+
return true;
|
|
1732
|
+
}
|
|
1733
|
+
const projectCtx = getImportedProject(ctx.db, ctx.projects, projectId);
|
|
1734
|
+
if (!projectCtx) {
|
|
1735
|
+
notFound(res, `Project not found: ${projectId}`);
|
|
1736
|
+
return true;
|
|
1737
|
+
}
|
|
1738
|
+
try {
|
|
1739
|
+
sendJson2(res, 200, {
|
|
1740
|
+
projectId,
|
|
1741
|
+
...await loadProjectDiffView(projectCtx, url.searchParams)
|
|
1742
|
+
});
|
|
1743
|
+
} catch (error) {
|
|
1744
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1745
|
+
sendJson2(res, 400, { error: message });
|
|
1746
|
+
}
|
|
1747
|
+
return true;
|
|
1748
|
+
}
|
|
1749
|
+
if (pathname === "/api/reports") {
|
|
1750
|
+
const projectId = url.searchParams.get("projectId");
|
|
1751
|
+
if (!projectId) {
|
|
1752
|
+
sendJson2(res, 400, { error: "projectId query parameter is required." });
|
|
1753
|
+
return true;
|
|
1754
|
+
}
|
|
1755
|
+
const projectCtx = getImportedProject(ctx.db, ctx.projects, projectId);
|
|
1756
|
+
if (!projectCtx) {
|
|
1757
|
+
notFound(res, `Project not found: ${projectId}`);
|
|
1758
|
+
return true;
|
|
1759
|
+
}
|
|
1760
|
+
sendJson2(res, 200, {
|
|
1761
|
+
projectId,
|
|
1762
|
+
...await loadProjectReportsView(projectCtx)
|
|
1763
|
+
});
|
|
1764
|
+
return true;
|
|
1765
|
+
}
|
|
1766
|
+
if (pathname === "/api/bundles/export") {
|
|
1767
|
+
const projectId = url.searchParams.get("projectId");
|
|
1768
|
+
if (!projectId) {
|
|
1769
|
+
sendJson2(res, 400, { error: "projectId query parameter is required." });
|
|
1770
|
+
return true;
|
|
1771
|
+
}
|
|
1772
|
+
const projectCtx = getImportedProject(ctx.db, ctx.projects, projectId);
|
|
1773
|
+
if (!projectCtx) {
|
|
1774
|
+
notFound(res, `Project not found: ${projectId}`);
|
|
1775
|
+
return true;
|
|
1776
|
+
}
|
|
1777
|
+
try {
|
|
1778
|
+
sendJson2(res, 200, await loadBundleExportView(projectCtx, url.searchParams));
|
|
1779
|
+
} catch (error) {
|
|
1780
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1781
|
+
sendJson2(res, 400, { error: message });
|
|
1782
|
+
}
|
|
1783
|
+
return true;
|
|
1784
|
+
}
|
|
1785
|
+
return false;
|
|
1786
|
+
}
|
|
1787
|
+
|
|
1788
|
+
// packages/studio/src/server.ts
|
|
1789
|
+
var DEFAULT_HOST = "127.0.0.1";
|
|
1790
|
+
var DEFAULT_PORT = 7340;
|
|
1791
|
+
function badRequest(res, message) {
|
|
1792
|
+
res.writeHead(400, {
|
|
1793
|
+
"content-type": "application/json; charset=utf-8",
|
|
1794
|
+
"cache-control": "no-store"
|
|
1795
|
+
});
|
|
1796
|
+
res.end(JSON.stringify({ error: message }));
|
|
1797
|
+
}
|
|
1798
|
+
function resolveHost(options) {
|
|
1799
|
+
if (options.server === true) {
|
|
1800
|
+
return options.host ?? "0.0.0.0";
|
|
1801
|
+
}
|
|
1802
|
+
return options.host ?? DEFAULT_HOST;
|
|
1803
|
+
}
|
|
1804
|
+
function createStudioServer(options = {}) {
|
|
1805
|
+
const host = resolveHost(options);
|
|
1806
|
+
const port = options.port ?? DEFAULT_PORT;
|
|
1807
|
+
let contextPromise = options.context ? Promise.resolve(options.context) : void 0;
|
|
1808
|
+
if (host === "0.0.0.0") {
|
|
1809
|
+
console.warn(
|
|
1810
|
+
"[AgentInspect studio] Binding to 0.0.0.0 exposes workspace evidence on the network. Use 127.0.0.1 unless you accept that risk."
|
|
1811
|
+
);
|
|
1812
|
+
if (options.auth !== "basic") {
|
|
1813
|
+
console.warn(
|
|
1814
|
+
"[AgentInspect studio] Non-localhost binding without --auth basic is discouraged for production use."
|
|
1815
|
+
);
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
const server = createServer(async (req, res) => {
|
|
1819
|
+
try {
|
|
1820
|
+
const method = req.method ?? "GET";
|
|
1821
|
+
const url = new URL(req.url ?? "/", `http://${host}:${port}`);
|
|
1822
|
+
const pathname = url.pathname;
|
|
1823
|
+
if (!contextPromise) {
|
|
1824
|
+
contextPromise = createStudioContext(options);
|
|
1825
|
+
}
|
|
1826
|
+
const ctx = await contextPromise;
|
|
1827
|
+
const httpConfig = resolveHttpIngestConfig(options, ctx.registry.ingest?.http);
|
|
1828
|
+
if (isHttpIngestRoute(pathname, httpConfig)) {
|
|
1829
|
+
const handled2 = await handleHttpIngestRequest(req, res, ctx, options, pathname);
|
|
1830
|
+
if (handled2) return;
|
|
1831
|
+
}
|
|
1832
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
1833
|
+
return badRequest(res, "Only GET is supported.");
|
|
1834
|
+
}
|
|
1835
|
+
if (pathname === "/" || pathname === "/index.html") {
|
|
1836
|
+
if (req.method === "HEAD") {
|
|
1837
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
1838
|
+
res.end();
|
|
1839
|
+
return;
|
|
1840
|
+
}
|
|
1841
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
1842
|
+
res.end(studioIndexHtml);
|
|
1843
|
+
return;
|
|
1844
|
+
}
|
|
1845
|
+
const handled = await handleStudioRoute(req, res, ctx, options, pathname, url);
|
|
1846
|
+
if (!handled) {
|
|
1847
|
+
res.writeHead(404, {
|
|
1848
|
+
"content-type": "application/json; charset=utf-8",
|
|
1849
|
+
"cache-control": "no-store"
|
|
1850
|
+
});
|
|
1851
|
+
res.end(JSON.stringify({ error: `Unknown route: ${pathname}` }));
|
|
1852
|
+
}
|
|
1853
|
+
} catch (error) {
|
|
1854
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1855
|
+
res.writeHead(500, {
|
|
1856
|
+
"content-type": "application/json; charset=utf-8",
|
|
1857
|
+
"cache-control": "no-store"
|
|
1858
|
+
});
|
|
1859
|
+
res.end(JSON.stringify({ error: message }));
|
|
1860
|
+
}
|
|
1861
|
+
});
|
|
1862
|
+
return server;
|
|
1863
|
+
}
|
|
1864
|
+
async function startStudioServer(options = {}) {
|
|
1865
|
+
const host = resolveHost(options);
|
|
1866
|
+
const port = options.port ?? DEFAULT_PORT;
|
|
1867
|
+
const ctx = options.context ?? await createStudioContext(options);
|
|
1868
|
+
const server = createStudioServer({ ...options, context: ctx });
|
|
1869
|
+
return new Promise((resolve, reject) => {
|
|
1870
|
+
server.once("error", reject);
|
|
1871
|
+
server.listen(port, host, () => {
|
|
1872
|
+
const address = server.address();
|
|
1873
|
+
const resolvedPort = typeof address === "object" && address ? address.port : port;
|
|
1874
|
+
resolve({
|
|
1875
|
+
host,
|
|
1876
|
+
port: resolvedPort,
|
|
1877
|
+
url: `http://${host === "0.0.0.0" ? "127.0.0.1" : host}:${resolvedPort}/`,
|
|
1878
|
+
mode: "studio",
|
|
1879
|
+
...options.workspacePath !== void 0 ? { workspacePath: options.workspacePath } : {},
|
|
1880
|
+
dbPath: ctx.dbPath,
|
|
1881
|
+
registryName: ctx.registry.name,
|
|
1882
|
+
projectCount: ctx.projects.length
|
|
1883
|
+
});
|
|
1884
|
+
});
|
|
1885
|
+
});
|
|
1886
|
+
}
|
|
1887
|
+
var DEFAULT_GITHUB_TOKEN_ENV = "GITHUB_TOKEN";
|
|
1888
|
+
var GITHUB_API_BASE = "https://api.github.com";
|
|
1889
|
+
function resolveTokenEnv(registry, override) {
|
|
1890
|
+
const fromRegistry = registry.ingest?.github?.tokenEnv?.trim();
|
|
1891
|
+
const envName = override?.trim() || fromRegistry || DEFAULT_GITHUB_TOKEN_ENV;
|
|
1892
|
+
if (!/^[A-Z][A-Z0-9_]*$/.test(envName)) {
|
|
1893
|
+
throw new Error("token env name must be an uppercase identifier");
|
|
1894
|
+
}
|
|
1895
|
+
return envName;
|
|
1896
|
+
}
|
|
1897
|
+
function resolveToken(envName) {
|
|
1898
|
+
const token = process.env[envName]?.trim();
|
|
1899
|
+
if (!token) {
|
|
1900
|
+
throw new Error(`missing GitHub token in environment variable ${envName}`);
|
|
1901
|
+
}
|
|
1902
|
+
return token;
|
|
1903
|
+
}
|
|
1904
|
+
function githubHeaders(token) {
|
|
1905
|
+
return {
|
|
1906
|
+
Authorization: `Bearer ${token}`,
|
|
1907
|
+
Accept: "application/vnd.github+json",
|
|
1908
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
1909
|
+
"User-Agent": "agent-inspect-studio-ingest"
|
|
1910
|
+
};
|
|
1911
|
+
}
|
|
1912
|
+
async function readResponseBody(response, maxBytes) {
|
|
1913
|
+
try {
|
|
1914
|
+
return await readBoundedResponseBody(response, maxBytes);
|
|
1915
|
+
} catch (error) {
|
|
1916
|
+
if (error instanceof IngestLimitError && error.code === "INGEST_SIZE_LIMIT") {
|
|
1917
|
+
throw new Error("artifact exceeds size limit");
|
|
1918
|
+
}
|
|
1919
|
+
throw error;
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
async function downloadGitHubArtifactArchive(options) {
|
|
1923
|
+
const maxBytes = resolveIngestMaxBytes(options.maxBytes);
|
|
1924
|
+
const fetchFn = options.fetchImpl ?? fetch;
|
|
1925
|
+
const { owner, name } = parseGitHubRepo(options.repo);
|
|
1926
|
+
const runId = options.runId.trim();
|
|
1927
|
+
const artifactName = options.artifactName.trim();
|
|
1928
|
+
if (!/^\d+$/.test(runId)) {
|
|
1929
|
+
throw new Error("run-id must be a numeric workflow run id");
|
|
1930
|
+
}
|
|
1931
|
+
if (artifactName === "") {
|
|
1932
|
+
throw new Error("artifact name must be non-empty");
|
|
1933
|
+
}
|
|
1934
|
+
const listUrl = `${GITHUB_API_BASE}/repos/${owner}/${name}/actions/runs/${runId}/artifacts`;
|
|
1935
|
+
const listResponse = await fetchFn(listUrl, {
|
|
1936
|
+
headers: githubHeaders(options.token)
|
|
1937
|
+
});
|
|
1938
|
+
if (!listResponse.ok) {
|
|
1939
|
+
throw new Error(`GitHub artifact lookup failed (${listResponse.status})`);
|
|
1940
|
+
}
|
|
1941
|
+
const payload = await listResponse.json();
|
|
1942
|
+
const artifact = payload.artifacts?.find((item) => item.name === artifactName);
|
|
1943
|
+
if (!artifact?.archive_download_url) {
|
|
1944
|
+
throw new Error(`artifact not found for run ${runId}: ${artifactName}`);
|
|
1945
|
+
}
|
|
1946
|
+
if (artifact.expired === true) {
|
|
1947
|
+
throw new Error(`artifact expired for run ${runId}: ${artifactName}`);
|
|
1948
|
+
}
|
|
1949
|
+
if (typeof artifact.size_in_bytes === "number" && artifact.size_in_bytes > maxBytes) {
|
|
1950
|
+
throw new Error("artifact exceeds size limit");
|
|
1951
|
+
}
|
|
1952
|
+
const downloadResponse = await fetchFn(artifact.archive_download_url, {
|
|
1953
|
+
headers: githubHeaders(options.token),
|
|
1954
|
+
redirect: "follow"
|
|
1955
|
+
});
|
|
1956
|
+
if (!downloadResponse.ok) {
|
|
1957
|
+
throw new Error(`GitHub artifact download failed (${downloadResponse.status})`);
|
|
1958
|
+
}
|
|
1959
|
+
return readResponseBody(downloadResponse, maxBytes);
|
|
1960
|
+
}
|
|
1961
|
+
async function importGitHubArtifact(options) {
|
|
1962
|
+
const registryImportWarnings = [];
|
|
1963
|
+
const errors = [];
|
|
1964
|
+
if (!options.enabled) {
|
|
1965
|
+
return {
|
|
1966
|
+
skipped: true,
|
|
1967
|
+
reason: "GitHub artifact ingest is disabled; use studio import github explicitly",
|
|
1968
|
+
imported: false,
|
|
1969
|
+
registryImportWarnings,
|
|
1970
|
+
errors
|
|
1971
|
+
};
|
|
1972
|
+
}
|
|
1973
|
+
let token;
|
|
1974
|
+
let tokenEnv;
|
|
1975
|
+
try {
|
|
1976
|
+
const { owner, name } = parseGitHubRepo(options.repo);
|
|
1977
|
+
tokenEnv = resolveTokenEnv(options.registry, options.tokenEnv);
|
|
1978
|
+
token = resolveToken(tokenEnv);
|
|
1979
|
+
const sourceKey = buildGitHubArtifactSourceKey({
|
|
1980
|
+
owner,
|
|
1981
|
+
repo: name,
|
|
1982
|
+
runId: options.runId,
|
|
1983
|
+
artifactName: options.artifactName
|
|
1984
|
+
});
|
|
1985
|
+
const archive = await downloadGitHubArtifactArchive({
|
|
1986
|
+
repo: options.repo,
|
|
1987
|
+
runId: options.runId,
|
|
1988
|
+
artifactName: options.artifactName,
|
|
1989
|
+
token,
|
|
1990
|
+
...options.fetchImpl !== void 0 ? { fetchImpl: options.fetchImpl } : {}
|
|
1991
|
+
});
|
|
1992
|
+
const contentHash = createHash("sha256").update(archive).digest("hex");
|
|
1993
|
+
const existing = findIngestFileBySourceKey(options.db, sourceKey);
|
|
1994
|
+
if (existing && existing.contentHash === contentHash) {
|
|
1995
|
+
return {
|
|
1996
|
+
skipped: false,
|
|
1997
|
+
imported: false,
|
|
1998
|
+
sourceKey,
|
|
1999
|
+
contentHash,
|
|
2000
|
+
destPath: existing.destPath,
|
|
2001
|
+
registryImportWarnings,
|
|
2002
|
+
errors
|
|
2003
|
+
};
|
|
2004
|
+
}
|
|
2005
|
+
const dirs = resolveImportDirs(options.registryPath, options.registry);
|
|
2006
|
+
const fileName = `${options.artifactName}.zip`;
|
|
2007
|
+
const destPath = uniqueDestPath(dirs.bundlesDir, fileName, contentHash);
|
|
2008
|
+
assertPathUnderRoot(destPath, dirs.registryDir);
|
|
2009
|
+
try {
|
|
2010
|
+
await withAtomicStagingDir(dirs.bundlesDir, async (stagingDir) => {
|
|
2011
|
+
const stagedPath = path10.join(stagingDir, fileName);
|
|
2012
|
+
await writeFile(stagedPath, archive);
|
|
2013
|
+
await promoteStagingPath(stagedPath, destPath);
|
|
2014
|
+
});
|
|
2015
|
+
const importedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2016
|
+
insertIngestFile(options.db, {
|
|
2017
|
+
sourceKey,
|
|
2018
|
+
sourceName: fileName,
|
|
2019
|
+
destPath,
|
|
2020
|
+
kind: "bundle",
|
|
2021
|
+
contentHash,
|
|
2022
|
+
importedAt
|
|
2023
|
+
});
|
|
2024
|
+
} catch (error) {
|
|
2025
|
+
await rm(destPath, { force: true }).catch(() => void 0);
|
|
2026
|
+
throw error;
|
|
2027
|
+
}
|
|
2028
|
+
const registryImport = await importStudioRegistry({
|
|
2029
|
+
db: options.db,
|
|
2030
|
+
registry: options.registry,
|
|
2031
|
+
registryPath: options.registryPath
|
|
2032
|
+
});
|
|
2033
|
+
registryImportWarnings.push(...registryImport.warnings);
|
|
2034
|
+
return {
|
|
2035
|
+
skipped: false,
|
|
2036
|
+
imported: true,
|
|
2037
|
+
sourceKey,
|
|
2038
|
+
contentHash,
|
|
2039
|
+
destPath,
|
|
2040
|
+
registryImportWarnings,
|
|
2041
|
+
errors
|
|
2042
|
+
};
|
|
2043
|
+
} catch (error) {
|
|
2044
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2045
|
+
errors.push(sanitizeSafeErrorMessage(message, token));
|
|
2046
|
+
return {
|
|
2047
|
+
skipped: false,
|
|
2048
|
+
imported: false,
|
|
2049
|
+
registryImportWarnings,
|
|
2050
|
+
errors
|
|
2051
|
+
};
|
|
2052
|
+
}
|
|
2053
|
+
}
|
|
2054
|
+
async function runStudioGitHubArtifactImport(options) {
|
|
2055
|
+
const cwd = options.cwd ?? process.cwd();
|
|
2056
|
+
const registryPath = await resolveStudioRegistryPath({
|
|
2057
|
+
...options.workspacePath !== void 0 ? { workspacePath: options.workspacePath } : {},
|
|
2058
|
+
cwd
|
|
2059
|
+
});
|
|
2060
|
+
const registryRead = await readStudioRegistryFile(registryPath);
|
|
2061
|
+
if (!registryRead.ok || registryRead.registry === void 0) {
|
|
2062
|
+
throw new Error(registryRead.errors.join("; ") || "invalid studio registry");
|
|
2063
|
+
}
|
|
2064
|
+
const dbPath = resolveStudioDbPath({
|
|
2065
|
+
...options.dbPath !== void 0 ? { dbPath: options.dbPath } : {},
|
|
2066
|
+
cwd
|
|
2067
|
+
});
|
|
2068
|
+
const db = openStudioDb(dbPath);
|
|
2069
|
+
return importGitHubArtifact({
|
|
2070
|
+
db,
|
|
2071
|
+
registryPath,
|
|
2072
|
+
registry: registryRead.registry,
|
|
2073
|
+
repo: options.repo,
|
|
2074
|
+
runId: options.runId,
|
|
2075
|
+
artifactName: options.artifact,
|
|
2076
|
+
enabled: true,
|
|
2077
|
+
...options.tokenEnv !== void 0 ? { tokenEnv: options.tokenEnv } : {},
|
|
2078
|
+
...options.fetchImpl !== void 0 ? { fetchImpl: options.fetchImpl } : {}
|
|
2079
|
+
});
|
|
2080
|
+
}
|
|
2081
|
+
async function pathExists(filePath) {
|
|
2082
|
+
try {
|
|
2083
|
+
await access(filePath);
|
|
2084
|
+
return true;
|
|
2085
|
+
} catch {
|
|
2086
|
+
return false;
|
|
2087
|
+
}
|
|
2088
|
+
}
|
|
2089
|
+
async function validateBundleDirectory(bundleDir) {
|
|
2090
|
+
const errors = [];
|
|
2091
|
+
const metadataPath = path10.join(bundleDir, "metadata.json");
|
|
2092
|
+
if (!await pathExists(metadataPath)) {
|
|
2093
|
+
errors.push("bundle missing metadata.json");
|
|
2094
|
+
return errors;
|
|
2095
|
+
}
|
|
2096
|
+
try {
|
|
2097
|
+
const raw = await readFile(metadataPath, "utf8");
|
|
2098
|
+
const parsed = JSON.parse(raw);
|
|
2099
|
+
if (typeof parsed.agentInspectVersion !== "string") {
|
|
2100
|
+
errors.push("bundle metadata.json missing agentInspectVersion");
|
|
2101
|
+
}
|
|
2102
|
+
if (!Array.isArray(parsed.runIds) || parsed.runIds.length === 0) {
|
|
2103
|
+
errors.push("bundle metadata.json missing runIds");
|
|
2104
|
+
}
|
|
2105
|
+
} catch {
|
|
2106
|
+
errors.push("bundle metadata.json is invalid JSON");
|
|
2107
|
+
}
|
|
2108
|
+
return errors;
|
|
2109
|
+
}
|
|
2110
|
+
async function hashBundleContents(bundleDir) {
|
|
2111
|
+
const hash = createHash("sha256");
|
|
2112
|
+
const walk = async (dir, relPrefix) => {
|
|
2113
|
+
const entries = (await readdir(dir, { withFileTypes: true })).sort(
|
|
2114
|
+
(a, b) => a.name.localeCompare(b.name)
|
|
2115
|
+
);
|
|
2116
|
+
for (const entry of entries) {
|
|
2117
|
+
const abs = path10.join(dir, entry.name);
|
|
2118
|
+
const rel = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
|
|
2119
|
+
const info = await lstat(abs);
|
|
2120
|
+
if (info.isSymbolicLink()) {
|
|
2121
|
+
throw new IngestLimitError(
|
|
2122
|
+
"INGEST_SYMLINK_REJECTED",
|
|
2123
|
+
"symbolic links are not allowed for ingest"
|
|
2124
|
+
);
|
|
2125
|
+
}
|
|
2126
|
+
if (info.isDirectory()) {
|
|
2127
|
+
await walk(abs, rel);
|
|
2128
|
+
} else if (info.isFile()) {
|
|
2129
|
+
hash.update(rel);
|
|
2130
|
+
hash.update("\0");
|
|
2131
|
+
hash.update(await readFile(abs));
|
|
2132
|
+
hash.update("\0");
|
|
2133
|
+
}
|
|
2134
|
+
}
|
|
2135
|
+
};
|
|
2136
|
+
await walk(bundleDir, "");
|
|
2137
|
+
return hash.digest("hex");
|
|
2138
|
+
}
|
|
2139
|
+
async function copyDirectoryRecursive(sourceDir, destDir) {
|
|
2140
|
+
await mkdir(destDir, { recursive: true });
|
|
2141
|
+
const entries = await readdir(sourceDir, { withFileTypes: true });
|
|
2142
|
+
for (const entry of entries) {
|
|
2143
|
+
const from = path10.join(sourceDir, entry.name);
|
|
2144
|
+
const to = path10.join(destDir, entry.name);
|
|
2145
|
+
const info = await lstat(from);
|
|
2146
|
+
if (info.isSymbolicLink()) {
|
|
2147
|
+
throw new IngestLimitError(
|
|
2148
|
+
"INGEST_SYMLINK_REJECTED",
|
|
2149
|
+
"symbolic links are not allowed for ingest"
|
|
2150
|
+
);
|
|
2151
|
+
}
|
|
2152
|
+
if (info.isDirectory()) {
|
|
2153
|
+
await copyDirectoryRecursive(from, to);
|
|
2154
|
+
} else if (info.isFile()) {
|
|
2155
|
+
await copyFile(from, to);
|
|
2156
|
+
}
|
|
2157
|
+
}
|
|
2158
|
+
}
|
|
2159
|
+
async function importBundleUpload(options) {
|
|
2160
|
+
const registryImportWarnings = [];
|
|
2161
|
+
const errors = [];
|
|
2162
|
+
if (!options.enabled) {
|
|
2163
|
+
return {
|
|
2164
|
+
skipped: true,
|
|
2165
|
+
reason: "bundle upload ingest is disabled; use studio import bundle explicitly",
|
|
2166
|
+
imported: false,
|
|
2167
|
+
errors,
|
|
2168
|
+
registryImportWarnings
|
|
2169
|
+
};
|
|
2170
|
+
}
|
|
2171
|
+
const bundlePath = path10.resolve(options.bundlePath);
|
|
2172
|
+
try {
|
|
2173
|
+
await lstatRegularDirectory(bundlePath);
|
|
2174
|
+
} catch (error) {
|
|
2175
|
+
if (error instanceof IngestLimitError) {
|
|
2176
|
+
return {
|
|
2177
|
+
skipped: false,
|
|
2178
|
+
imported: false,
|
|
2179
|
+
errors: [error.message],
|
|
2180
|
+
registryImportWarnings
|
|
2181
|
+
};
|
|
2182
|
+
}
|
|
2183
|
+
return {
|
|
2184
|
+
skipped: false,
|
|
2185
|
+
imported: false,
|
|
2186
|
+
errors: ["bundle path does not exist"],
|
|
2187
|
+
registryImportWarnings
|
|
2188
|
+
};
|
|
2189
|
+
}
|
|
2190
|
+
const validationErrors = await validateBundleDirectory(bundlePath);
|
|
2191
|
+
if (validationErrors.length > 0) {
|
|
2192
|
+
return {
|
|
2193
|
+
skipped: false,
|
|
2194
|
+
imported: false,
|
|
2195
|
+
errors: validationErrors,
|
|
2196
|
+
registryImportWarnings
|
|
2197
|
+
};
|
|
2198
|
+
}
|
|
2199
|
+
let maxBytes;
|
|
2200
|
+
try {
|
|
2201
|
+
maxBytes = resolveIngestMaxBytes(
|
|
2202
|
+
options.maxBytes ?? options.registry.ingest?.bundleUpload?.maxBytes
|
|
2203
|
+
);
|
|
2204
|
+
await measureDirectoryBytes(bundlePath, maxBytes);
|
|
2205
|
+
} catch (error) {
|
|
2206
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2207
|
+
return {
|
|
2208
|
+
skipped: false,
|
|
2209
|
+
imported: false,
|
|
2210
|
+
errors: [message],
|
|
2211
|
+
registryImportWarnings
|
|
2212
|
+
};
|
|
2213
|
+
}
|
|
2214
|
+
let contentHash;
|
|
2215
|
+
try {
|
|
2216
|
+
contentHash = await hashBundleContents(bundlePath);
|
|
2217
|
+
} catch (error) {
|
|
2218
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2219
|
+
return {
|
|
2220
|
+
skipped: false,
|
|
2221
|
+
imported: false,
|
|
2222
|
+
errors: [message],
|
|
2223
|
+
registryImportWarnings
|
|
2224
|
+
};
|
|
2225
|
+
}
|
|
2226
|
+
const sourceKey = `bundle:${bundlePath}`;
|
|
2227
|
+
const existing = findIngestFileBySourceKey(options.db, sourceKey);
|
|
2228
|
+
if (existing && existing.contentHash === contentHash) {
|
|
2229
|
+
return {
|
|
2230
|
+
skipped: false,
|
|
2231
|
+
imported: false,
|
|
2232
|
+
destPath: existing.destPath,
|
|
2233
|
+
sourceKey,
|
|
2234
|
+
errors,
|
|
2235
|
+
registryImportWarnings
|
|
2236
|
+
};
|
|
2237
|
+
}
|
|
2238
|
+
const dirs = resolveImportDirs(options.registryPath, options.registry);
|
|
2239
|
+
const folderName = path10.basename(bundlePath);
|
|
2240
|
+
const destPath = uniqueDestPath(dirs.bundlesDir, folderName, contentHash);
|
|
2241
|
+
assertPathUnderRoot(destPath, dirs.registryDir);
|
|
2242
|
+
try {
|
|
2243
|
+
await withAtomicStagingDir(dirs.bundlesDir, async (stagingDir) => {
|
|
2244
|
+
const stagedDest = path10.join(stagingDir, folderName);
|
|
2245
|
+
await copyDirectoryRecursive(bundlePath, stagedDest);
|
|
2246
|
+
await promoteStagingPath(stagedDest, destPath);
|
|
2247
|
+
});
|
|
2248
|
+
insertIngestFile(options.db, {
|
|
2249
|
+
sourceKey,
|
|
2250
|
+
sourceName: folderName,
|
|
2251
|
+
destPath,
|
|
2252
|
+
kind: "bundle",
|
|
2253
|
+
contentHash,
|
|
2254
|
+
importedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2255
|
+
});
|
|
2256
|
+
const registryImport = await importStudioRegistry({
|
|
2257
|
+
db: options.db,
|
|
2258
|
+
registry: options.registry,
|
|
2259
|
+
registryPath: options.registryPath
|
|
2260
|
+
});
|
|
2261
|
+
registryImportWarnings.push(...registryImport.warnings);
|
|
2262
|
+
return {
|
|
2263
|
+
skipped: false,
|
|
2264
|
+
imported: true,
|
|
2265
|
+
destPath,
|
|
2266
|
+
sourceKey,
|
|
2267
|
+
errors,
|
|
2268
|
+
registryImportWarnings
|
|
2269
|
+
};
|
|
2270
|
+
} catch (error) {
|
|
2271
|
+
await rm(destPath, { recursive: true, force: true }).catch(() => void 0);
|
|
2272
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2273
|
+
return {
|
|
2274
|
+
skipped: false,
|
|
2275
|
+
imported: false,
|
|
2276
|
+
errors: [message],
|
|
2277
|
+
registryImportWarnings
|
|
2278
|
+
};
|
|
2279
|
+
}
|
|
2280
|
+
}
|
|
2281
|
+
async function runStudioBundleUploadImport(options) {
|
|
2282
|
+
const cwd = options.cwd ?? process.cwd();
|
|
2283
|
+
const registryPath = await resolveStudioRegistryPath({
|
|
2284
|
+
...options.workspacePath !== void 0 ? { workspacePath: options.workspacePath } : {},
|
|
2285
|
+
cwd
|
|
2286
|
+
});
|
|
2287
|
+
const registryRead = await readStudioRegistryFile(registryPath);
|
|
2288
|
+
if (!registryRead.ok || registryRead.registry === void 0) {
|
|
2289
|
+
throw new Error(registryRead.errors.join("; ") || "invalid studio registry");
|
|
2290
|
+
}
|
|
2291
|
+
const dbPath = resolveStudioDbPath({
|
|
2292
|
+
...options.dbPath !== void 0 ? { dbPath: options.dbPath } : {},
|
|
2293
|
+
cwd
|
|
2294
|
+
});
|
|
2295
|
+
const db = openStudioDb(dbPath);
|
|
2296
|
+
return importBundleUpload({
|
|
2297
|
+
db,
|
|
2298
|
+
registryPath,
|
|
2299
|
+
registry: registryRead.registry,
|
|
2300
|
+
bundlePath: options.bundlePath,
|
|
2301
|
+
enabled: true
|
|
2302
|
+
});
|
|
2303
|
+
}
|
|
2304
|
+
|
|
2305
|
+
export { HTTP_INGEST_ARTIFACT_PATH, HTTP_INGEST_BUNDLE_PATH, createStudioContext, createStudioServer, downloadGitHubArtifactArchive, extractIngestTokenFromRequest, handleHttpIngestRequest, importBundleUpload, importFileDrop, importFileDropFromRegistry, importGitHubArtifact, isHttpIngestRoute, isIngestTokenValid, openStudioDb, parseStudioRegistry, readStudioRegistryFile, resolveHttpIngestConfig, resolveIngestToken, resolveIngestTokenEnv, resolveStudioDbPath, resolveStudioRegistryPath, runStudioBundleUploadImport, runStudioFileDropImport, runStudioGitHubArtifactImport, startStudioServer, studioIndexHtml, summarizeProjects, validateBundleDirectory };
|
|
2306
|
+
//# sourceMappingURL=index.mjs.map
|
|
2307
|
+
//# sourceMappingURL=index.mjs.map
|