@kousaku-maron/diffshape 0.6.0 → 0.8.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.
@@ -1,13 +1,15 @@
1
1
  // ../core/src/git.ts
2
2
  import { execFile, spawn } from "node:child_process";
3
- import { readFile, stat } from "node:fs/promises";
3
+ import { copyFile, mkdtemp, readFile, rm, stat } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
4
5
  import { join } from "node:path";
5
6
  import { promisify } from "node:util";
6
7
  var execFileAsync = promisify(execFile);
7
- async function git(cwd, args) {
8
+ async function git(cwd, args, env) {
8
9
  const { stdout } = await execFileAsync("git", args, {
9
10
  cwd,
10
- maxBuffer: 512 * 1024 * 1024
11
+ maxBuffer: 512 * 1024 * 1024,
12
+ ...env ? { env: { ...process.env, ...env } } : {}
11
13
  });
12
14
  return stdout;
13
15
  }
@@ -84,6 +86,37 @@ async function untrackedFiles(root) {
84
86
  );
85
87
  return files.filter((f) => f !== null);
86
88
  }
89
+ async function worktreeTree(root) {
90
+ const tmp = await mkdtemp(join(tmpdir(), "diffshape-index-"));
91
+ try {
92
+ const env = { GIT_INDEX_FILE: join(tmp, "index") };
93
+ const real = (await git(root, ["rev-parse", "--path-format=absolute", "--git-path", "index"])).trim();
94
+ await copyFile(real, env.GIT_INDEX_FILE).catch(() => {
95
+ });
96
+ await git(root, ["add", "-A"], env);
97
+ return (await git(root, ["write-tree"], env)).trim();
98
+ } finally {
99
+ await rm(tmp, { recursive: true, force: true });
100
+ }
101
+ }
102
+ var SNAPSHOT_REF = "refs/diffshape/before-fix";
103
+ async function snapshotWorktree(root) {
104
+ const tree = await worktreeTree(root);
105
+ const head = await git(root, ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"]).then(
106
+ (s) => s.trim(),
107
+ () => ""
108
+ // no commit yet
109
+ );
110
+ const who = { GIT_AUTHOR_NAME: "diffshape", GIT_AUTHOR_EMAIL: "diffshape@localhost", GIT_COMMITTER_NAME: "diffshape", GIT_COMMITTER_EMAIL: "diffshape@localhost" };
111
+ const commit = (await git(root, ["commit-tree", tree, ...head ? ["-p", head] : [], "-m", "diffshape: the working tree before an AI fix"], who)).trim();
112
+ await git(root, ["update-ref", SNAPSHOT_REF, commit]);
113
+ return commit;
114
+ }
115
+ async function changedSince(root, commit) {
116
+ const tree = await worktreeTree(root);
117
+ const out = await git(root, ["-c", "core.quotePath=false", "diff", "--name-only", "-z", "--no-renames", commit, tree, "--"]);
118
+ return out.split("\0").filter(Boolean);
119
+ }
87
120
  async function readBlob(root, source, path) {
88
121
  if (source.kind === "worktree") {
89
122
  try {
@@ -204,6 +237,31 @@ function hostAllowed(listenHost, hostHeader) {
204
237
  return false;
205
238
  }
206
239
  }
240
+ var isLoopback = (host) => LOOPBACK.has(host);
241
+ function postAllowed(listenHost, headers) {
242
+ if (!LOOPBACK.has(listenHost) || !headers.host || !headers.origin) return false;
243
+ if (!(headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) return false;
244
+ try {
245
+ return new URL(headers.origin).host === headers.host;
246
+ } catch {
247
+ return false;
248
+ }
249
+ }
250
+ var MAX_BODY = 2 * 1024 * 1024;
251
+ async function readJSON(req) {
252
+ const chunks = [];
253
+ let size = 0;
254
+ for await (const chunk of req) {
255
+ size += chunk.length;
256
+ if (size > MAX_BODY) throw new HttpError(413, "request too large");
257
+ chunks.push(chunk);
258
+ }
259
+ try {
260
+ return JSON.parse(Buffer.concat(chunks).toString("utf8") || "null");
261
+ } catch {
262
+ throw new HttpError(400, "invalid JSON");
263
+ }
264
+ }
207
265
  var MIME = {
208
266
  ".html": "text/html; charset=utf-8",
209
267
  ".js": "text/javascript; charset=utf-8",
@@ -219,6 +277,15 @@ async function startServer(opts) {
219
277
  return;
220
278
  }
221
279
  const url = new URL(req.url ?? "/", "http://localhost");
280
+ const post = opts.post?.[url.pathname];
281
+ if (post) {
282
+ if (req.method !== "POST") throw new HttpError(405, "POST only");
283
+ if (!postAllowed(opts.host, req.headers)) throw new HttpError(403, "forbidden origin");
284
+ const body2 = await post(await readJSON(req), url);
285
+ res.writeHead(200, { "content-type": MIME[".json"], "cache-control": "no-store" });
286
+ res.end(JSON.stringify(body2 ?? null));
287
+ return;
288
+ }
222
289
  const handler = opts.api[url.pathname];
223
290
  if (handler) {
224
291
  const body2 = await handler(url);
@@ -278,6 +345,320 @@ function openBrowser(url) {
278
345
  }).unref();
279
346
  }
280
347
 
348
+ // ../core/src/agent.ts
349
+ import { execFile as execFile2, spawn as spawn3 } from "node:child_process";
350
+ import { access, constants, mkdtemp as mkdtemp2, readFile as readFile3, realpath, rm as rm2, writeFile } from "node:fs/promises";
351
+ import { homedir, tmpdir as tmpdir2 } from "node:os";
352
+ import { delimiter, join as join3 } from "node:path";
353
+ var AGENT_IDS = ["claude", "codex"];
354
+ var AGENT_LABEL = { claude: "Claude Code", codex: "Codex" };
355
+ var CLAUDE_EFFORTS = ["low", "medium", "high", "xhigh", "max"];
356
+ var FALLBACK_OPTIONS = {
357
+ claude: {
358
+ label: AGENT_LABEL.claude,
359
+ models: [
360
+ { id: "opus", label: "Opus", efforts: CLAUDE_EFFORTS },
361
+ { id: "fable", label: "Fable", efforts: CLAUDE_EFFORTS },
362
+ { id: "sonnet", label: "Sonnet", efforts: CLAUDE_EFFORTS },
363
+ { id: "haiku", label: "Haiku", efforts: CLAUDE_EFFORTS }
364
+ ],
365
+ defaultEfforts: CLAUDE_EFFORTS
366
+ },
367
+ codex: { label: AGENT_LABEL.codex, models: [], defaultEfforts: ["low", "medium", "high"] }
368
+ };
369
+ var validModel = (m) => /^[A-Za-z0-9][A-Za-z0-9._:/\[\]-]{0,99}$/.test(m);
370
+ var validEffort = (e) => /^[a-z]{1,20}$/.test(e);
371
+ var nullable = (type) => ({ type: [type, "null"] });
372
+ var REVIEW_SCHEMA = {
373
+ type: "object",
374
+ additionalProperties: false,
375
+ required: ["comments"],
376
+ properties: {
377
+ comments: {
378
+ type: "array",
379
+ items: {
380
+ type: "object",
381
+ additionalProperties: false,
382
+ required: ["module", "body", "target", "path", "side", "line", "endLine", "code"],
383
+ properties: {
384
+ module: { type: "string" },
385
+ body: { type: "string" },
386
+ target: nullable("string"),
387
+ path: nullable("string"),
388
+ side: { type: ["string", "null"], enum: ["old", "new", null] },
389
+ line: nullable("integer"),
390
+ endLine: nullable("integer"),
391
+ code: nullable("string")
392
+ }
393
+ }
394
+ }
395
+ }
396
+ };
397
+ var ENV = { claude: "DIFFSHAPE_CLAUDE", codex: "DIFFSHAPE_CODEX" };
398
+ var FALLBACK = { claude: [join3(homedir(), ".claude", "local", "claude")], codex: [] };
399
+ var executable = (path) => access(path, constants.X_OK).then(
400
+ () => true,
401
+ () => false
402
+ );
403
+ async function findAgent(id) {
404
+ const forced = process.env[ENV[id]];
405
+ if (forced !== void 0) return forced && await executable(forced) ? forced : null;
406
+ const names2 = process.platform === "win32" ? [`${id}.exe`] : [id];
407
+ const dirs = (process.env.PATH ?? "").split(delimiter).filter(Boolean);
408
+ for (const p of [...dirs.flatMap((d) => names2.map((n) => join3(d, n))), ...FALLBACK[id]]) if (await executable(p)) return p;
409
+ return null;
410
+ }
411
+ async function detectAgents() {
412
+ const found = await Promise.all(AGENT_IDS.map(findAgent));
413
+ return AGENT_IDS.filter((_, i) => found[i] !== null);
414
+ }
415
+ function capture(bin, args, cwd, input = "", timeout = 15e3) {
416
+ return new Promise((resolve, reject) => {
417
+ const child = execFile2(bin, args, { cwd, timeout, maxBuffer: 32 * 1024 * 1024 }, (err, stdout) => err ? reject(err) : resolve(stdout));
418
+ child.stdin?.on("error", () => {
419
+ });
420
+ child.stdin?.end(input);
421
+ });
422
+ }
423
+ var strings = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string" && validEffort(x)) : [];
424
+ var union = (lists) => [...new Set(lists.flat())];
425
+ async function claudeOptions(bin, cwd) {
426
+ const ask = JSON.stringify({ type: "control_request", request_id: "diffshape-models", request: { subtype: "initialize" } });
427
+ const out = await capture(bin, ["-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose"], cwd, `${ask}
428
+ `);
429
+ for (const line of out.split("\n")) {
430
+ let o;
431
+ try {
432
+ o = JSON.parse(line);
433
+ } catch {
434
+ continue;
435
+ }
436
+ const list = o?.type === "control_response" ? (o.response?.response ?? o.response)?.models : void 0;
437
+ if (!Array.isArray(list)) continue;
438
+ const all = list.filter((m) => typeof m?.value === "string" && validModel(m.value));
439
+ const models = all.filter((m) => m.value !== "default").map((m) => ({ id: m.value, label: String(m.displayName ?? m.value), ...m.description ? { description: String(m.description) } : {}, efforts: strings(m.supportedEffortLevels) }));
440
+ if (!models.length) break;
441
+ const byDefault = all.find((m) => m.value === "default");
442
+ return { label: AGENT_LABEL.claude, models, defaultEfforts: byDefault ? strings(byDefault.supportedEffortLevels) : union(models.map((m) => m.efforts)) };
443
+ }
444
+ throw new Error("no models in the answer");
445
+ }
446
+ async function codexOptions(bin, cwd) {
447
+ const list = JSON.parse(await capture(bin, ["debug", "models"], cwd)).models;
448
+ if (!Array.isArray(list)) throw new Error("no models in the answer");
449
+ const models = list.filter((m) => typeof m?.slug === "string" && validModel(m.slug) && m.visibility === "list").map((m) => ({
450
+ id: m.slug,
451
+ label: String(m.display_name ?? m.slug),
452
+ ...m.description ? { description: String(m.description) } : {},
453
+ efforts: strings((m.supported_reasoning_levels ?? []).map((l) => l?.effort))
454
+ }));
455
+ if (!models.length) throw new Error("no models in the answer");
456
+ return { label: AGENT_LABEL.codex, models, defaultEfforts: union(models.map((m) => m.efforts)) };
457
+ }
458
+ async function agentOptions(id, cwd) {
459
+ const bin = await findAgent(id);
460
+ if (!bin) return FALLBACK_OPTIONS[id];
461
+ const [options, version] = await Promise.all([
462
+ (id === "claude" ? claudeOptions(bin, cwd) : codexOptions(bin, cwd)).catch(() => FALLBACK_OPTIONS[id]),
463
+ // "codex-cli 0.153.4", "2.1.0 (Claude Code)"
464
+ capture(bin, ["--version"], cwd).then(
465
+ (out) => /\d+\.\d+\.\d+[\w.-]*/.exec(out)?.[0],
466
+ () => void 0
467
+ )
468
+ ]);
469
+ return { ...options, ...version ? { version } : {} };
470
+ }
471
+ var AgentCancelled = class extends Error {
472
+ constructor() {
473
+ super("cancelled");
474
+ }
475
+ };
476
+ var firstLine = (s, max = 200) => {
477
+ const l = s.trim().split("\n")[0] ?? "";
478
+ return l.length > max ? `${l.slice(0, max)}\u2026` : l;
479
+ };
480
+ function claudeEvent(o, out, log) {
481
+ if (o.type === "assistant" && Array.isArray(o.message?.content)) {
482
+ for (const c of o.message.content) {
483
+ if (c.type === "text" && c.text?.trim()) log(firstLine(c.text));
484
+ if (c.type === "tool_use" && c.name !== "StructuredOutput") {
485
+ const i = c.input ?? {};
486
+ const what = i.description ?? i.file_path ?? i.path ?? i.pattern ?? i.command ?? "";
487
+ log(what ? `${c.name}: ${firstLine(String(what))}` : String(c.name));
488
+ }
489
+ }
490
+ }
491
+ if (o.type === "result") {
492
+ out.text = typeof o.result === "string" ? o.result : "";
493
+ out.structured = o.structured_output;
494
+ if (o.is_error) out.error = out.text || String(o.subtype ?? "error");
495
+ }
496
+ }
497
+ function errorText(message2) {
498
+ const s = String(message2 ?? "");
499
+ try {
500
+ const o = JSON.parse(s);
501
+ return String(o?.error?.message ?? o?.message ?? s);
502
+ } catch {
503
+ return s;
504
+ }
505
+ }
506
+ function shellWord(w) {
507
+ let out = "";
508
+ let i = 0;
509
+ while (i < w.length) {
510
+ const c = w[i];
511
+ if (c === "'") {
512
+ const end = w.indexOf("'", i + 1);
513
+ if (end < 0) return null;
514
+ out += w.slice(i + 1, end);
515
+ i = end + 1;
516
+ } else if (c === '"') {
517
+ for (i++; i < w.length && w[i] !== '"'; i++) {
518
+ if (w[i] === "\\" && '"\\$`'.includes(w[i + 1] ?? "")) i++;
519
+ out += w[i];
520
+ }
521
+ if (i >= w.length) return null;
522
+ i++;
523
+ } else if (/\s/.test(c)) {
524
+ return null;
525
+ } else {
526
+ if (c === "\\" && i + 1 < w.length) i++;
527
+ out += w[i++];
528
+ }
529
+ }
530
+ return out;
531
+ }
532
+ function codexEvent(o, out, log, review) {
533
+ const item = o.item;
534
+ if (o.type === "item.started" && item?.type === "command_execution") {
535
+ const m = /^\S+ -lc ([\s\S]+)$/.exec(String(item.command));
536
+ log(`$ ${firstLine((m && shellWord(m[1])) ?? String(item.command))}`);
537
+ }
538
+ if (o.type === "item.completed" && item) {
539
+ if (item.type === "agent_message" && typeof item.text === "string") {
540
+ out.text = item.text;
541
+ if (!(review && item.text.trimStart().startsWith("{"))) log(firstLine(item.text));
542
+ }
543
+ if (item.type === "file_change" && Array.isArray(item.changes)) log(`Edit: ${item.changes.map((c) => String(c.path)).join(", ")}`);
544
+ if (item.type === "error") log(firstLine(String(item.message)));
545
+ }
546
+ if (o.type === "error") out.error = errorText(o.message);
547
+ if (o.type === "turn.failed") out.error = errorText(o.error?.message);
548
+ }
549
+ function toItems(value) {
550
+ const list = value?.comments;
551
+ if (!Array.isArray(list)) throw new Error("\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u306E\u7B54\u3048\u306B\u30B3\u30E1\u30F3\u30C8\u306E\u4E00\u89A7\u304C\u3042\u308A\u307E\u305B\u3093");
552
+ const str2 = (v) => typeof v === "string" && v !== "" ? v : null;
553
+ const int = (v) => typeof v === "number" && Number.isInteger(v) && v > 0 ? v : null;
554
+ return list.filter((c) => !!c && typeof c === "object" && typeof c.module === "string" && typeof c.body === "string" && c.body.trim() !== "").map((c) => ({
555
+ module: c.module,
556
+ body: c.body.trim(),
557
+ target: str2(c.target),
558
+ path: str2(c.path),
559
+ side: c.side === "old" || c.side === "new" ? c.side : null,
560
+ line: int(c.line),
561
+ endLine: int(c.endLine),
562
+ // not trimmed: the code is matched against the file's lines
563
+ code: typeof c.code === "string" ? c.code : null
564
+ }));
565
+ }
566
+ function parseAnswer(text) {
567
+ try {
568
+ return JSON.parse(text);
569
+ } catch {
570
+ throw new Error(`\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u306E\u7B54\u3048\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F: ${firstLine(text) || "\uFF08\u7A7A\uFF09"}`);
571
+ }
572
+ }
573
+ async function runAgent(run2) {
574
+ const bin = await findAgent(run2.agent);
575
+ if (!bin) throw new Error(`${run2.agent} \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093`);
576
+ const review = run2.kind === "review";
577
+ if (run2.model !== void 0 && !validModel(run2.model)) throw new Error(`\u30E2\u30C7\u30EB\u540D\u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093: ${run2.model}`);
578
+ if (run2.effort !== void 0 && !validEffort(run2.effort)) throw new Error(`effort \u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093: ${run2.effort}`);
579
+ const tmp = await mkdtemp2(join3(tmpdir2(), "diffshape-agent-"));
580
+ try {
581
+ let args;
582
+ const last = join3(tmp, "last.txt");
583
+ if (run2.agent === "claude") {
584
+ args = ["-p", "--permission-mode", review ? "plan" : "auto", "--output-format", "stream-json", "--verbose"];
585
+ if (run2.model) args.push("--model", run2.model);
586
+ if (run2.effort) args.push("--effort", run2.effort);
587
+ if (review) args.push("--json-schema", JSON.stringify(REVIEW_SCHEMA));
588
+ } else {
589
+ args = ["exec", "--sandbox", review ? "read-only" : "workspace-write", "--json", "-o", last, "-C", run2.cwd];
590
+ if (run2.model) args.push("-m", run2.model);
591
+ if (run2.effort) args.push("-c", `model_reasoning_effort="${run2.effort}"`);
592
+ if (review) {
593
+ const schema = join3(tmp, "schema.json");
594
+ await writeFile(schema, JSON.stringify(REVIEW_SCHEMA));
595
+ args.push("--output-schema", schema);
596
+ }
597
+ args.push("-");
598
+ }
599
+ const roots = [.../* @__PURE__ */ new Set([run2.cwd, await realpath(run2.cwd).catch(() => run2.cwd)])].map((r) => `${r}/`).sort((x, y) => y.length - x.length);
600
+ const fromRoot = (text) => roots.reduce((l, r) => l.split(r).join(""), text);
601
+ let lastLine = "";
602
+ const log = (text) => {
603
+ const line = fromRoot(text);
604
+ if (line !== lastLine) run2.onLog(lastLine = line);
605
+ };
606
+ const out = { text: "" };
607
+ const code = await new Promise((resolve, reject) => {
608
+ const proc = spawn3(bin, args, { cwd: run2.cwd, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32" });
609
+ const kill = (sig) => {
610
+ try {
611
+ if (process.platform !== "win32" && proc.pid) process.kill(-proc.pid, sig);
612
+ else proc.kill(sig);
613
+ } catch {
614
+ }
615
+ };
616
+ const stop = () => {
617
+ kill("SIGTERM");
618
+ setTimeout(() => kill("SIGKILL"), 3e3).unref();
619
+ };
620
+ if (run2.signal?.aborted) stop();
621
+ run2.signal?.addEventListener("abort", stop, { once: true });
622
+ let buf = "";
623
+ proc.stdout.setEncoding("utf8").on("data", (d) => {
624
+ buf += d;
625
+ let nl;
626
+ while ((nl = buf.indexOf("\n")) >= 0) {
627
+ const line = buf.slice(0, nl);
628
+ buf = buf.slice(nl + 1);
629
+ let o;
630
+ try {
631
+ o = JSON.parse(line);
632
+ } catch {
633
+ continue;
634
+ }
635
+ if (run2.agent === "claude") claudeEvent(o, out, log);
636
+ else codexEvent(o, out, log, review);
637
+ }
638
+ });
639
+ let err = "";
640
+ proc.stderr.setEncoding("utf8").on("data", (d) => err = (err + d).slice(-2e3));
641
+ proc.on("error", reject);
642
+ proc.on("close", (c) => {
643
+ run2.signal?.removeEventListener("abort", stop);
644
+ if (c !== 0 && !out.error && !out.text) out.error = err.trim() || `${run2.agent} \u304C\u7D42\u4E86\u30B3\u30FC\u30C9 ${c} \u3067\u7D42\u308F\u308A\u307E\u3057\u305F`;
645
+ resolve(c);
646
+ });
647
+ proc.stdin.on("error", () => {
648
+ });
649
+ proc.stdin.end(run2.prompt);
650
+ });
651
+ if (run2.signal?.aborted) throw new AgentCancelled();
652
+ if (out.error) throw new Error(out.error);
653
+ if (code !== 0) throw new Error(`${run2.agent} \u304C\u7D42\u4E86\u30B3\u30FC\u30C9 ${code} \u3067\u7D42\u308F\u308A\u307E\u3057\u305F`);
654
+ if (run2.agent === "codex") out.text = await readFile3(last, "utf8").catch(() => "") || out.text;
655
+ if (!review) return { text: fromRoot(out.text.trim()) };
656
+ return { text: "", comments: toItems(out.structured ?? parseAnswer(out.text)) };
657
+ } finally {
658
+ await rm2(tmp, { recursive: true, force: true });
659
+ }
660
+ }
661
+
281
662
  // ../dbshape/src/analyze.ts
282
663
  import { posix as posix2 } from "node:path";
283
664
  import { loadModule, parseSync } from "libpg-query";
@@ -2493,16 +2874,114 @@ var fileApi = {
2493
2874
  // ../fileshape/src/index.ts
2494
2875
  var fileAnalyzer = { id: "file", analyze: analyzeFiles, api: fileApi };
2495
2876
 
2877
+ // src/agent.ts
2878
+ var LOG_LINES = 300;
2879
+ var MAX_PROMPT = 1024 * 1024;
2880
+ var bad = (message2) => {
2881
+ throw new HttpError(400, message2);
2882
+ };
2883
+ function parseStart(body) {
2884
+ const b = body && typeof body === "object" ? body : {};
2885
+ if (b.kind !== "review" && b.kind !== "fix") bad("kind \u306F review \u304B fix \u3067\u3059");
2886
+ if (!AGENT_IDS.includes(b.agent)) bad("agent \u306F claude \u304B codex \u3067\u3059");
2887
+ if (typeof b.prompt !== "string" || !b.prompt.trim() || b.prompt.length > MAX_PROMPT) bad("prompt \u304C\u306A\u3044\u304B\u3001\u9577\u3059\u304E\u307E\u3059");
2888
+ const agent = b.agent;
2889
+ const model = typeof b.model === "string" && b.model.trim() ? b.model.trim() : void 0;
2890
+ const effort = typeof b.effort === "string" && b.effort ? b.effort : void 0;
2891
+ if (model !== void 0 && !validModel(model)) bad(`\u30E2\u30C7\u30EB\u540D\u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093: ${model}`);
2892
+ if (effort !== void 0 && !validEffort(effort)) bad(`effort \u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093: ${effort}`);
2893
+ return { kind: b.kind, agent, prompt: b.prompt, ...model ? { model } : {}, ...effort ? { effort } : {} };
2894
+ }
2895
+ var AgentJobs = class {
2896
+ /** `enabled` is false when the server is open to the network: nobody else may start an agent here */
2897
+ constructor(enabled) {
2898
+ this.enabled = enabled;
2899
+ }
2900
+ job = null;
2901
+ abort = null;
2902
+ running = Promise.resolve();
2903
+ found = null;
2904
+ seq = 0;
2905
+ /** The agents on this machine with their models, asked once: they do not change while the app runs */
2906
+ agents(root) {
2907
+ return this.found ??= detectAgents().then((ids) => Promise.all(ids.map(async (id) => ({ id, ...await agentOptions(id, root) }))));
2908
+ }
2909
+ async state(sources) {
2910
+ const agents = this.enabled ? await this.agents(sources.root) : [];
2911
+ const ids = agents.map((a) => a.id);
2912
+ const reason = !this.enabled ? "--host \u3067\u307B\u304B\u306E\u30DE\u30B7\u30F3\u306B\u516C\u958B\u3057\u3066\u3044\u308B\u3068\u304D\u306F\u4F7F\u3048\u307E\u305B\u3093" : sources.target.kind !== "worktree" ? "\u4F5C\u696D\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3068\u306E\u6BD4\u8F03\uFF08target \u304C . \u304B working\uFF09\u306E\u3068\u304D\u3060\u3051\u4F7F\u3048\u307E\u3059" : ids.length === 0 ? "claude \u3082 codex \u3082\u898B\u3064\u304B\u308A\u307E\u305B\u3093" : void 0;
2913
+ return { available: !reason, ...reason ? { reason } : {}, agents, job: this.job };
2914
+ }
2915
+ async start(sources, body) {
2916
+ const req = parseStart(body);
2917
+ const state = await this.state(sources);
2918
+ if (!state.available) throw new HttpError(409, state.reason);
2919
+ const agent = state.agents.find((a) => a.id === req.agent);
2920
+ if (!agent) throw new HttpError(409, `${req.agent} \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093`);
2921
+ const model = req.model === void 0 ? void 0 : agent.models.find((m) => m.id === req.model);
2922
+ if (req.model !== void 0 && !model) throw new HttpError(400, `${agent.label} \u306B\u306A\u3044\u30E2\u30C7\u30EB\u3067\u3059: ${req.model}`);
2923
+ if (req.effort !== void 0 && !(model?.efforts ?? agent.defaultEfforts).includes(req.effort)) throw new HttpError(400, `${model?.label ?? agent.label} \u306B\u306A\u3044 effort \u3067\u3059: ${req.effort}`);
2924
+ if (this.job?.status === "running") throw new HttpError(409, "\u307B\u304B\u306E AI \u306E\u5B9F\u884C\u304C\u7D42\u308F\u3063\u3066\u3044\u307E\u305B\u3093");
2925
+ const { prompt, ...chosen } = req;
2926
+ const job = { id: ++this.seq, ...chosen, status: "running", startedAt: Date.now(), log: [] };
2927
+ const abort = new AbortController();
2928
+ this.job = job;
2929
+ this.abort = abort;
2930
+ this.running = (async () => {
2931
+ let status = "done";
2932
+ let commit;
2933
+ try {
2934
+ if (req.kind === "fix") {
2935
+ commit = await snapshotWorktree(sources.root);
2936
+ job.snapshot = SNAPSHOT_REF;
2937
+ }
2938
+ const r = await runAgent({
2939
+ ...chosen,
2940
+ cwd: sources.root,
2941
+ prompt,
2942
+ signal: abort.signal,
2943
+ onLog: (line) => {
2944
+ job.log.push(line);
2945
+ if (job.log.length > LOG_LINES) job.log.splice(0, job.log.length - LOG_LINES);
2946
+ }
2947
+ });
2948
+ job.text = r.text;
2949
+ if (r.comments) job.comments = r.comments;
2950
+ } catch (e) {
2951
+ status = e instanceof AgentCancelled ? "cancelled" : "failed";
2952
+ if (status === "failed") job.error = e instanceof Error ? e.message : String(e);
2953
+ }
2954
+ if (commit) job.changedFiles = await changedSince(sources.root, commit).catch(() => void 0);
2955
+ job.endedAt = Date.now();
2956
+ job.status = status;
2957
+ })();
2958
+ return job;
2959
+ }
2960
+ /** Stops the running job (nothing happens when none runs) */
2961
+ cancel() {
2962
+ if (this.job?.status === "running") this.abort?.abort();
2963
+ return this.job;
2964
+ }
2965
+ /** Resolves when no job runs any more */
2966
+ idle() {
2967
+ return this.running;
2968
+ }
2969
+ };
2970
+
2496
2971
  // src/app.ts
2497
2972
  var message = (e) => (e instanceof Error ? e.stderr || e.message : String(e)).trim();
2498
2973
  var App = class {
2499
- constructor(cwd, opts, analyzers) {
2974
+ constructor(cwd, opts, analyzers, appOpts = {}) {
2500
2975
  this.cwd = cwd;
2501
2976
  this.opts = opts;
2502
2977
  this.analyzers = analyzers;
2978
+ this.jobs = new AgentJobs(appOpts.agents ?? true);
2979
+ this.cleanId = appOpts.clean ? `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 7)}` : null;
2503
2980
  }
2504
2981
  sources;
2505
2982
  results = /* @__PURE__ */ new Map();
2983
+ jobs;
2984
+ cleanId;
2506
2985
  /** Resolves the comparison (errors like an unknown revision are thrown) and starts every module */
2507
2986
  async refresh() {
2508
2987
  this.sources = await resolveSources(this.cwd, this.opts);
@@ -2518,8 +2997,8 @@ var App = class {
2518
2997
  return this.info();
2519
2998
  }
2520
2999
  info() {
2521
- const { root, targetLabel, baseLabel } = this.sources;
2522
- return { repoRoot: root, targetLabel, baseLabel, modules: this.analyzers.map((a) => a.id) };
3000
+ const { root, targetLabel, baseLabel, base } = this.sources;
3001
+ return { repoRoot: root, targetLabel, baseLabel, baseRev: base.kind === "rev" ? base.rev : null, modules: this.analyzers.map((a) => a.id), clean: this.cleanId };
2523
3002
  }
2524
3003
  result(id) {
2525
3004
  return this.results.get(id) ?? Promise.resolve({ error: `unknown module: ${id}` });
@@ -2533,6 +3012,21 @@ var App = class {
2533
3012
  if ("error" in r) throw new HttpError(409, r.error);
2534
3013
  return handler(url, { sources: this.sources, data: r.data });
2535
3014
  }
3015
+ /** Whether an AI review or fix can run here, with which agents, and the running (or last) job */
3016
+ agentState() {
3017
+ return this.jobs.state(this.sources);
3018
+ }
3019
+ /** Starts an AI review or fix from what the screen posted ({ kind, agent, prompt, model?, effort? }) */
3020
+ startAgent(body) {
3021
+ return this.jobs.start(this.sources, body);
3022
+ }
3023
+ cancelAgent() {
3024
+ return this.jobs.cancel();
3025
+ }
3026
+ /** Resolves when no AI job runs any more */
3027
+ agentIdle() {
3028
+ return this.jobs.idle();
3029
+ }
2536
3030
  };
2537
3031
 
2538
3032
  // src/server.ts
@@ -2540,13 +3034,18 @@ import { fileURLToPath } from "node:url";
2540
3034
  var UI_DIR = fileURLToPath(new URL("./ui/", import.meta.url));
2541
3035
  function startServer2(app, host, port) {
2542
3036
  const api = {
2543
- "/api/info": async (url) => url.searchParams.get("refresh") === "1" ? app.refresh() : app.info()
3037
+ "/api/info": async (url) => url.searchParams.get("refresh") === "1" ? app.refresh() : app.info(),
3038
+ "/api/agent": () => app.agentState()
3039
+ };
3040
+ const post = {
3041
+ "/api/agent/start": (body) => app.startAgent(body),
3042
+ "/api/agent/cancel": async () => app.cancelAgent()
2544
3043
  };
2545
3044
  for (const a of app.analyzers) {
2546
3045
  api[`/api/module/${a.id}`] = () => app.result(a.id);
2547
3046
  for (const name of Object.keys(a.api ?? {})) api[`/api/module/${a.id}/${name}`] = (url) => app.call(a.id, name, url);
2548
3047
  }
2549
- return startServer({ uiDir: UI_DIR, host, port, api });
3048
+ return startServer({ uiDir: UI_DIR, host, port, api, post });
2550
3049
  }
2551
3050
 
2552
3051
  // src/cli.ts
@@ -2563,7 +3062,8 @@ var COMMON = ` --merge-base compare-with \u3068 target \u306E\u5206\u5C90
2563
3062
  --port <n> \u30DD\u30FC\u30C8\u756A\u53F7\uFF08\u30C7\u30D5\u30A9\u30EB\u30C8 4977\u3001\u4F7F\u7528\u4E2D\u306A\u3089 +1\uFF09
2564
3063
  --host <host> \u5F85\u3061\u53D7\u3051\u30DB\u30B9\u30C8\uFF08\u30C7\u30D5\u30A9\u30EB\u30C8 127.0.0.1\u30020.0.0.0 \u306A\u3069\u306B\u3059\u308B\u3068\u540C\u3058\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\u304B\u3089
2565
3064
  \u30EA\u30DD\u30B8\u30C8\u30EA\u306E\u69CB\u6210\u304C\u898B\u3048\u308B\u306E\u3067\u6CE8\u610F\uFF09
2566
- --no-open \u30D6\u30E9\u30A6\u30B6\u3092\u81EA\u52D5\u3067\u958B\u304B\u306A\u3044`;
3065
+ --no-open \u30D6\u30E9\u30A6\u30B6\u3092\u81EA\u52D5\u3067\u958B\u304B\u306A\u3044
3066
+ --clean \u3053\u306E\u6BD4\u8F03\u306E\u30EC\u30D3\u30E5\u30FC\u30B3\u30E1\u30F3\u30C8\u3068\u78BA\u8A8D\u6E08\u307F\u306E\u30DE\u30FC\u30AF\u3092\u6D88\u3057\u3066\u304B\u3089\u958B\u304F`;
2567
3067
  var SCHEMA = ` --schema <glob> \u30B9\u30AD\u30FC\u30DE\u306E SQL \u30D5\u30A1\u30A4\u30EB\uFF08\u8907\u6570\u6307\u5B9A\u53EF\uFF09\u3002\u7701\u7565\u6642\u306F\u30EA\u30DD\u30B8\u30C8\u30EA\u5185\u306E\u3059\u3079\u3066\u306E atlas.hcl \u306E src \u3092\u8AAD\u3080
2568
3068
  DB \u304C\u8907\u6570\u3042\u308B\u3068\u304D\u306F --schema billing=services/billing/**/*.sql \u306E\u3088\u3046\u306B\u540D\u524D\u3092\u4ED8\u3051\u308B`;
2569
3069
  var HELP = {
@@ -2634,7 +3134,7 @@ function parseArgs(argv, command) {
2634
3134
  const fail = (msg) => {
2635
3135
  throw new UsageError(msg);
2636
3136
  };
2637
- const args = { port: 4977, host: "127.0.0.1", open: true, json: false, text: false, color: !!process.stdout.isTTY && !process.env.NO_COLOR, schema: [], only: fixed };
3137
+ const args = { port: 4977, host: "127.0.0.1", open: true, clean: false, json: false, text: false, color: !!process.stdout.isTTY && !process.env.NO_COLOR, schema: [], only: fixed };
2638
3138
  const positional = [];
2639
3139
  const allowed = (opt, ok) => ok || fail(`\u4E0D\u660E\u306A\u30AA\u30D7\u30B7\u30E7\u30F3: ${opt}`);
2640
3140
  for (let i = 0; i < argv.length; i++) {
@@ -2657,6 +3157,9 @@ function parseArgs(argv, command) {
2657
3157
  case "--no-open":
2658
3158
  args.open = false;
2659
3159
  break;
3160
+ case "--clean":
3161
+ args.clean = true;
3162
+ break;
2660
3163
  case "--schema":
2661
3164
  allowed(a, !fixed || fixed === "db");
2662
3165
  args.schema.push(argv[++i] ?? fail("--schema \u306B\u306F glob \u304C\u5FC5\u8981\u3067\u3059"));
@@ -2706,7 +3209,7 @@ async function run(command, argv) {
2706
3209
  }
2707
3210
  const all = [fileAnalyzer, depAnalyzer, dbAnalyzer({ schema: args.schema })];
2708
3211
  const analyzers = args.only ? all.filter((a) => a.id === args.only) : all;
2709
- const app = new App(process.cwd(), args, analyzers);
3212
+ const app = new App(process.cwd(), args, analyzers, { agents: isLoopback(args.host), clean: args.clean });
2710
3213
  try {
2711
3214
  await app.refresh();
2712
3215
  if (args.json || args.text) {
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  run
4
- } from "./chunk-AKBOSCJ7.js";
4
+ } from "./chunk-QXDXARRR.js";
5
5
 
6
6
  // src/bin/dbshape.ts
7
7
  void run("dbshape", process.argv.slice(2));
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  run
4
- } from "./chunk-AKBOSCJ7.js";
4
+ } from "./chunk-QXDXARRR.js";
5
5
 
6
6
  // src/bin/depshape.ts
7
7
  void run("depshape", process.argv.slice(2));
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  run
4
- } from "./chunk-AKBOSCJ7.js";
4
+ } from "./chunk-QXDXARRR.js";
5
5
 
6
6
  // src/bin/diffshape.ts
7
7
  void run("diffshape", process.argv.slice(2));
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  run
4
- } from "./chunk-AKBOSCJ7.js";
4
+ } from "./chunk-QXDXARRR.js";
5
5
 
6
6
  // src/bin/fileshape.ts
7
7
  void run("fileshape", process.argv.slice(2));