alibai 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/store.js CHANGED
@@ -25,18 +25,55 @@ async function createDirectory(path) {
25
25
  }
26
26
  }
27
27
  async function save(directory, run) {
28
- const path = (0, node_path_1.join)(directory, "run.json");
29
- (0, report_1.assertRun)(run, path);
30
- const temporary = (0, node_path_1.join)(directory, `.run-${(0, node_crypto_1.randomUUID)()}.tmp`);
28
+ (0, report_1.assertRun)(run, (0, node_path_1.join)(directory, "run.json"));
29
+ await saveJson(directory, "run.json", run);
30
+ }
31
+ async function saveJson(directory, name, value) {
32
+ const temporary = (0, node_path_1.join)(directory, `.${name}-${(0, node_crypto_1.randomUUID)()}.tmp`);
31
33
  try {
32
- await (0, promises_1.writeFile)(temporary, JSON.stringify(run, null, 2) + "\n", { flag: "wx", mode: 0o600 });
33
- await (0, promises_1.rename)(temporary, path);
34
+ await (0, promises_1.writeFile)(temporary, JSON.stringify(value, null, 2) + "\n", { flag: "wx", mode: 0o600 });
35
+ await (0, promises_1.rename)(temporary, (0, node_path_1.join)(directory, name));
34
36
  }
35
37
  catch (error) {
36
38
  await (0, promises_1.rm)(temporary, { force: true }).catch(() => { });
37
39
  throw error;
38
40
  }
39
41
  }
42
+ function isComment(value) {
43
+ if (!value || typeof value !== "object")
44
+ return false;
45
+ const { id, text, createdAt, updatedAt } = value;
46
+ return typeof id === "string" && id.length === 36 && report_1.runId.test(id) &&
47
+ typeof text === "string" && typeof createdAt === "string" && Number.isFinite(Date.parse(createdAt)) &&
48
+ (updatedAt === undefined || (typeof updatedAt === "string" && Number.isFinite(Date.parse(updatedAt))));
49
+ }
50
+ async function readComments(directory) {
51
+ const path = (0, node_path_1.join)(directory, "comments.json");
52
+ try {
53
+ if (!(await (0, promises_1.lstat)(path)).isFile())
54
+ throw new Error(`Expected a regular file at ${path}.`);
55
+ const file = await (0, promises_1.open)(path, node_fs_1.constants.O_RDONLY | node_fs_1.constants.O_NOFOLLOW | node_fs_1.constants.O_NONBLOCK);
56
+ try {
57
+ if (!(await file.stat()).isFile())
58
+ throw new Error(`Expected a regular file at ${path}.`);
59
+ const comments = (0, report_1.parseJson)(await file.readFile("utf8"), path);
60
+ if (!comments || typeof comments !== "object" || Array.isArray(comments) ||
61
+ !Object.entries(comments).every(([id, thread]) => id.length === 36 && report_1.runId.test(id) &&
62
+ Array.isArray(thread) && thread.every(isComment))) {
63
+ throw new Error(`Invalid comments in ${path}.`);
64
+ }
65
+ return comments;
66
+ }
67
+ finally {
68
+ await file.close();
69
+ }
70
+ }
71
+ catch (error) {
72
+ if (hasCode(error, "ENOENT"))
73
+ return {};
74
+ throw error;
75
+ }
76
+ }
40
77
  class RunStore {
41
78
  home;
42
79
  runs;
@@ -131,9 +168,9 @@ class RunStore {
131
168
  return;
132
169
  }
133
170
  }
134
- async mutate(id, edit) {
171
+ async existingDirectory(id) {
135
172
  if (!report_1.runId.test(id))
136
- throw new Error("--run must be a run UUID.");
173
+ return;
137
174
  const directory = (0, node_path_1.join)(this.runs, id);
138
175
  try {
139
176
  await requireDirectory(this.home);
@@ -142,9 +179,57 @@ class RunStore {
142
179
  }
143
180
  catch (error) {
144
181
  if (hasCode(error, "ENOENT"))
145
- throw new Error(`Run ${id} was not found.`);
182
+ return;
146
183
  throw error;
147
184
  }
185
+ return directory;
186
+ }
187
+ async comments(id) {
188
+ const directory = await this.existingDirectory(id);
189
+ if (!directory)
190
+ return;
191
+ await this.read(directory, id);
192
+ return readComments(directory);
193
+ }
194
+ async changeComment(id, exhibitId, change) {
195
+ if (!report_1.runId.test(exhibitId) || !report_1.runId.test(change.id))
196
+ return;
197
+ const directory = await this.existingDirectory(id);
198
+ if (!directory)
199
+ return;
200
+ return this.withRunLock(directory, id, async () => {
201
+ const { run } = await this.read(directory, id);
202
+ if (![...run.steps, ...run.checks].some((item) => item.id === exhibitId))
203
+ return;
204
+ const comments = await readComments(directory);
205
+ const thread = comments[exhibitId] ?? [];
206
+ const index = thread.findIndex((comment) => comment.id === change.id);
207
+ if (change.action === "delete") {
208
+ if (index === -1)
209
+ return thread;
210
+ thread.splice(index, 1);
211
+ }
212
+ else if (change.action === "add") {
213
+ if (index >= 0)
214
+ return thread[index].text === change.text ? thread : null;
215
+ thread.push({ id: change.id, text: change.text, createdAt: new Date().toISOString() });
216
+ }
217
+ else {
218
+ if (index === -1)
219
+ return null;
220
+ if (thread[index].text === change.text)
221
+ return thread;
222
+ thread[index] = { ...thread[index], text: change.text, updatedAt: new Date().toISOString() };
223
+ }
224
+ if (thread.length)
225
+ comments[exhibitId] = thread;
226
+ else
227
+ delete comments[exhibitId];
228
+ await saveJson(directory, "comments.json", comments);
229
+ return thread;
230
+ });
231
+ }
232
+ async withRunLock(directory, id, action) {
148
233
  const lock = (0, node_path_1.join)(directory, ".lock");
149
234
  const deadline = Date.now() + 5000;
150
235
  // shortcut: recover interrupted writers manually as lock age cannot prove that a writer has exited.
@@ -164,36 +249,48 @@ class RunStore {
164
249
  await (0, promises_2.setTimeout)(25);
165
250
  }
166
251
  }
167
- const copied = [];
168
252
  try {
169
- const stored = await this.read(directory, id);
170
- if (stored.run.verdict !== undefined)
171
- throw new Error(`Run ${id} is already completed.`);
172
- await edit(stored.run, async (source, name) => {
173
- const sourceStat = await (0, promises_1.stat)(source).catch((error) => {
174
- if (!hasCode(error, "ENOENT"))
175
- throw error;
176
- throw new Error(`Screenshot was not found: ${source}`);
177
- });
178
- if (!sourceStat.isFile())
179
- throw new Error(`Screenshot must be a regular file: ${source}`);
180
- await requireDirectory((0, node_path_1.join)(directory, "screenshots"));
181
- const relative = `screenshots/${name}${(0, node_path_1.extname)(source).toLowerCase()}`;
182
- const destination = (0, node_path_1.join)(directory, relative);
183
- await (0, promises_1.copyFile)(source, destination, node_fs_1.constants.COPYFILE_EXCL);
184
- copied.push(destination);
185
- return relative;
186
- });
187
- await save(directory, stored.run);
188
- return stored;
189
- }
190
- catch (error) {
191
- await Promise.allSettled(copied.map((path) => (0, promises_1.rm)(path, { force: true })));
192
- throw error;
253
+ return await action();
193
254
  }
194
255
  finally {
195
256
  await (0, promises_1.rmdir)(lock).catch(() => { });
196
257
  }
197
258
  }
259
+ async mutate(id, edit) {
260
+ if (!report_1.runId.test(id))
261
+ throw new Error("--run must be a run UUID.");
262
+ const directory = await this.existingDirectory(id);
263
+ if (!directory)
264
+ throw new Error(`Run ${id} was not found.`);
265
+ return this.withRunLock(directory, id, async () => {
266
+ const copied = [];
267
+ try {
268
+ const stored = await this.read(directory, id);
269
+ if (stored.run.verdict !== undefined)
270
+ throw new Error(`Run ${id} is already completed.`);
271
+ await edit(stored.run, async (source, name) => {
272
+ const sourceStat = await (0, promises_1.stat)(source).catch((error) => {
273
+ if (!hasCode(error, "ENOENT"))
274
+ throw error;
275
+ throw new Error(`Screenshot was not found: ${source}`);
276
+ });
277
+ if (!sourceStat.isFile())
278
+ throw new Error(`Screenshot must be a regular file: ${source}`);
279
+ await requireDirectory((0, node_path_1.join)(directory, "screenshots"));
280
+ const relative = `screenshots/${name}${(0, node_path_1.extname)(source).toLowerCase()}`;
281
+ const destination = (0, node_path_1.join)(directory, relative);
282
+ await (0, promises_1.copyFile)(source, destination, node_fs_1.constants.COPYFILE_EXCL);
283
+ copied.push(destination);
284
+ return relative;
285
+ });
286
+ await save(directory, stored.run);
287
+ return stored;
288
+ }
289
+ catch (error) {
290
+ await Promise.allSettled(copied.map((path) => (0, promises_1.rm)(path, { force: true })));
291
+ throw error;
292
+ }
293
+ });
294
+ }
198
295
  }
199
296
  exports.RunStore = RunStore;
package/dist/viewer.js CHANGED
@@ -8,6 +8,7 @@ const promises_1 = require("node:fs/promises");
8
8
  const node_http_1 = require("node:http");
9
9
  const node_path_1 = require("node:path");
10
10
  const store_1 = require("./store");
11
+ const report_1 = require("./report");
11
12
  const host = "127.0.0.1";
12
13
  const fonts = [
13
14
  "IBMPlexSans-Regular-Latin1.woff2", "IBMPlexSans-SemiBold-Latin1.woff2",
@@ -21,37 +22,95 @@ const assets = new Map([
21
22
  ["/viewer.css", ["viewer.css", "text/css; charset=utf-8"]],
22
23
  ["/viewer.js", ["viewer.js", "text/javascript; charset=utf-8"]],
23
24
  ["/messages.js", ["messages.js", "text/javascript; charset=utf-8"]],
25
+ ["/evidence.js", ["evidence.js", "text/javascript; charset=utf-8"]],
24
26
  ...fonts.map((file) => [`/fonts/${file}`, [`fonts/${file}`, "font/woff2"]]),
25
27
  ]);
26
28
  const imageTypes = new Map([
27
29
  [".png", "image/png"], [".jpg", "image/jpeg"], [".jpeg", "image/jpeg"], [".webp", "image/webp"],
28
30
  ]);
31
+ async function readComment(request) {
32
+ const chunks = [];
33
+ let size = 0;
34
+ for await (const chunk of request.iterator({ destroyOnReturn: false })) {
35
+ size += chunk.length;
36
+ if (size > 32768)
37
+ return { status: 413 };
38
+ chunks.push(chunk);
39
+ }
40
+ try {
41
+ const value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
42
+ if (typeof value?.id === "string" && value.id.length === 36 && report_1.runId.test(value.id)) {
43
+ const { id, action } = value;
44
+ if (action === "delete")
45
+ return { id, action };
46
+ if ((action === "add" || action === "edit") && typeof value.text === "string") {
47
+ const text = value.text.trim();
48
+ if (text.length > 0 && text.length <= 4000)
49
+ return { id, action, text };
50
+ }
51
+ }
52
+ }
53
+ catch {
54
+ // Malformed JSON is a bad request.
55
+ }
56
+ return { status: 400 };
57
+ }
29
58
  async function startViewer(root) {
30
59
  const store = new store_1.RunStore(root);
31
60
  const server = (0, node_http_1.createServer)(async (request, response) => {
32
61
  response.setHeader("Cache-Control", "no-store");
33
62
  response.setHeader("X-Content-Type-Options", "nosniff");
34
63
  response.setHeader("Cross-Origin-Resource-Policy", "same-origin");
35
- response.setHeader("Content-Security-Policy", "default-src 'none'; script-src 'self'; style-src 'self'; font-src 'self'; img-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'");
64
+ response.setHeader("Content-Security-Policy", "default-src 'none'; script-src 'self'; style-src 'self'; style-src-elem 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data:; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'");
36
65
  const send = (status, type, body) => {
37
66
  response.writeHead(status, { "Content-Type": type });
38
67
  response.end(body);
39
68
  };
40
69
  const text = (status, message) => send(status, "text/plain; charset=utf-8", message);
70
+ const json = (value) => send(200, "application/json; charset=utf-8", JSON.stringify(value));
41
71
  const address = server.address();
42
72
  if (!address || typeof address === "string" ||
43
73
  ![host, "localhost", "[::1]"].some((name) => request.headers.host === `${name}:${address.port}`)) {
44
74
  return text(403, "Forbidden. Open the 127.0.0.1 URL printed by alibai open.");
45
75
  }
46
- if (request.method !== "GET") {
47
- response.setHeader("Allow", "GET");
48
- return text(405, "Method not allowed.");
49
- }
50
76
  const path = request.url?.split("?", 1)[0] ?? "";
51
77
  const site = request.headers["sec-fetch-site"];
52
78
  if (path !== "/" && site && site !== "same-origin" && site !== "none")
53
79
  return text(403, "Forbidden.");
54
80
  try {
81
+ if (path.startsWith("/api/comments/")) {
82
+ const [, , , id, exhibit, ...rest] = path.split("/");
83
+ if (!report_1.runId.test(id) || (exhibit !== undefined && !report_1.runId.test(exhibit)) || rest.length) {
84
+ return text(400, "Invalid run or exhibit id.");
85
+ }
86
+ if (request.method === "GET" && !exhibit) {
87
+ const comments = await store.comments(id);
88
+ return comments === undefined ? text(404, "Run not found.") : json(comments);
89
+ }
90
+ if (request.method === "POST" && exhibit) {
91
+ if (request.headers.origin && request.headers.origin !== `http://${request.headers.host}`) {
92
+ return text(403, "Forbidden.");
93
+ }
94
+ if (request.headers["content-type"]?.split(";", 1)[0].trim() !== "application/json") {
95
+ return text(415, "Expected application/json.");
96
+ }
97
+ const comment = await readComment(request);
98
+ if ("status" in comment) {
99
+ request.resume();
100
+ return text(comment.status, "Invalid comment.");
101
+ }
102
+ const thread = await store.changeComment(id, exhibit, comment);
103
+ if (thread === null)
104
+ return text(409, "Comment changed.");
105
+ return thread === undefined ? text(404, "Run or exhibit not found.") : json(thread);
106
+ }
107
+ response.setHeader("Allow", exhibit ? "POST" : "GET");
108
+ return text(405, "Method not allowed.");
109
+ }
110
+ if (request.method !== "GET") {
111
+ response.setHeader("Allow", "GET");
112
+ return text(405, "Method not allowed.");
113
+ }
55
114
  const asset = assets.get(path);
56
115
  if (asset) {
57
116
  const [file, type] = asset;
@@ -59,9 +118,9 @@ async function startViewer(root) {
59
118
  }
60
119
  if (path === "/api/runs") {
61
120
  const { runs, invalidRuns } = await store.list();
62
- return send(200, "application/json; charset=utf-8", JSON.stringify({
121
+ return json({
63
122
  project: (0, node_path_1.basename)(root), runs: runs.map(({ run }) => run), invalidRuns,
64
- }));
123
+ });
65
124
  }
66
125
  const screenshot = /^\/screenshots\/([0-9a-f-]+)\/([a-zA-Z0-9_-]+\.[a-zA-Z0-9]+)$/.exec(path);
67
126
  if (screenshot) {
package/package.json CHANGED
@@ -1,8 +1,12 @@
1
1
  {
2
2
  "name": "alibai",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Record local test evidence for AI coding agents",
5
5
  "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/kut7728/alibi-for-ai.git"
9
+ },
6
10
  "bin": {
7
11
  "alibai": "dist/cli.js"
8
12
  },