forge-cw 0.1.12 → 0.1.13

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.js CHANGED
@@ -1,13 +1,36 @@
1
1
  #!/usr/bin/env node
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4
8
  var __esm = (fn, res) => function __init() {
5
9
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
10
  };
11
+ var __commonJS = (cb, mod) => function __require() {
12
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13
+ };
7
14
  var __export = (target, all) => {
8
15
  for (var name in all)
9
16
  __defProp(target, name, { get: all[name], enumerable: true });
10
17
  };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
+ // If the importer is in node compatibility mode or this is not an ESM
28
+ // file that has been converted to a CommonJS file using a Babel-
29
+ // compatible transform (i.e. "__esModule" has not been set), then set
30
+ // "default" to the CommonJS "module.exports" for node compatibility.
31
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
32
+ mod
33
+ ));
11
34
 
12
35
  // ../core/dist/db.js
13
36
  import { randomUUID } from "node:crypto";
@@ -71,6 +94,28 @@ var init_db = __esm({
71
94
  value TEXT NOT NULL,
72
95
  PRIMARY KEY (module_id, key)
73
96
  );
97
+
98
+ CREATE TABLE IF NOT EXISTS module_kv (
99
+ module_id TEXT NOT NULL,
100
+ key TEXT NOT NULL,
101
+ value TEXT NOT NULL,
102
+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),
103
+ PRIMARY KEY (module_id, key)
104
+ );
105
+
106
+ CREATE TABLE IF NOT EXISTS module_notifications (
107
+ module_id TEXT NOT NULL,
108
+ key TEXT NOT NULL,
109
+ kind TEXT NOT NULL,
110
+ title TEXT NOT NULL DEFAULT '',
111
+ body TEXT,
112
+ version TEXT,
113
+ count INTEGER,
114
+ label TEXT,
115
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
116
+ seen_at TEXT,
117
+ PRIMARY KEY (module_id, key)
118
+ );
74
119
  `);
75
120
  }
76
121
  listTables() {
@@ -159,6 +204,57 @@ var init_db = __esm({
159
204
  setModuleSetting(moduleId, key, value) {
160
205
  this.db.prepare("INSERT INTO module_settings (module_id, key, value) VALUES (?, ?, ?) ON CONFLICT(module_id, key) DO UPDATE SET value = excluded.value").run(moduleId, key, value);
161
206
  }
207
+ kvGet(moduleId, key) {
208
+ const row = this.db.prepare("SELECT value FROM module_kv WHERE module_id = ? AND key = ?").get(moduleId, key);
209
+ return row?.value;
210
+ }
211
+ kvSet(moduleId, key, json) {
212
+ this.db.prepare("INSERT INTO module_kv (module_id, key, value) VALUES (?, ?, ?) ON CONFLICT(module_id, key) DO UPDATE SET value = excluded.value, updated_at = datetime('now')").run(moduleId, key, json);
213
+ }
214
+ kvDelete(moduleId, key) {
215
+ this.db.prepare("DELETE FROM module_kv WHERE module_id = ? AND key = ?").run(moduleId, key);
216
+ }
217
+ kvList(moduleId, prefix = "") {
218
+ const rows = this.db.prepare("SELECT key FROM module_kv WHERE module_id = ? AND substr(key, 1, ?) = ? ORDER BY key").all(moduleId, prefix.length, prefix);
219
+ return rows.map((r) => r.key);
220
+ }
221
+ // true when the row is new or its version changed; a changed version is unseen again
222
+ upsertNotification(row) {
223
+ const current = this.db.prepare("SELECT version, title, body, count, label FROM module_notifications WHERE module_id = ? AND key = ?").get(row.moduleId, row.key);
224
+ const version = row.version ?? null;
225
+ if (current && current.version === version) {
226
+ this.db.prepare("UPDATE module_notifications SET title = ?, body = ?, count = ?, label = ? WHERE module_id = ? AND key = ?").run(row.title, row.body ?? null, row.count ?? null, row.label ?? null, row.moduleId, row.key);
227
+ return false;
228
+ }
229
+ this.db.prepare(`INSERT INTO module_notifications (module_id, key, kind, title, body, version, count, label) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
230
+ ON CONFLICT(module_id, key) DO UPDATE SET kind = excluded.kind, title = excluded.title, body = excluded.body, version = excluded.version,
231
+ count = excluded.count, label = excluded.label, created_at = datetime('now'), seen_at = NULL`).run(row.moduleId, row.key, row.kind, row.title, row.body ?? null, version, row.count ?? null, row.label ?? null);
232
+ return true;
233
+ }
234
+ deleteNotification(moduleId, key) {
235
+ this.db.prepare("DELETE FROM module_notifications WHERE module_id = ? AND key = ?").run(moduleId, key);
236
+ }
237
+ listNotifications() {
238
+ const rows = this.db.prepare("SELECT * FROM module_notifications ORDER BY created_at, rowid").all();
239
+ return rows.map((r) => ({
240
+ moduleId: r.module_id,
241
+ key: r.key,
242
+ kind: r.kind,
243
+ title: r.title,
244
+ body: r.body ?? void 0,
245
+ version: r.version ?? void 0,
246
+ count: r.count ?? void 0,
247
+ label: r.label ?? void 0,
248
+ createdAt: r.created_at,
249
+ seenAt: r.seen_at ?? null
250
+ }));
251
+ }
252
+ markNotificationsSeen(moduleId) {
253
+ this.db.prepare("UPDATE module_notifications SET seen_at = datetime('now') WHERE module_id = ? AND seen_at IS NULL").run(moduleId);
254
+ }
255
+ deleteModuleSetting(moduleId, key) {
256
+ this.db.prepare("DELETE FROM module_settings WHERE module_id = ? AND key = ?").run(moduleId, key);
257
+ }
162
258
  listActionLogs(opts) {
163
259
  const { moduleId, limit = 50 } = opts;
164
260
  let sql = "SELECT * FROM action_logs";
@@ -238,6 +334,8 @@ var init_modules = __esm({
238
334
  try {
239
335
  const raw = readFileSync(manifestPath, "utf-8");
240
336
  const manifest = JSON.parse(raw);
337
+ if (manifest.sdk !== void 0)
338
+ return void 0;
241
339
  this.loaded.set(dirName, manifest);
242
340
  return manifest;
243
341
  } catch {
@@ -268,11 +366,18 @@ var init_runner = __esm({
268
366
  "use strict";
269
367
  ActionRunner = class {
270
368
  async exec(command, options) {
271
- return new Promise((resolve5) => {
369
+ return this.run("sh", ["-c", command], options);
370
+ }
371
+ // no shell: the args reach the program as they are
372
+ async spawn(command, args, options) {
373
+ return this.run(command, args, options);
374
+ }
375
+ run(file, args, options) {
376
+ return new Promise((resolve10) => {
272
377
  let output = "";
273
378
  let timedOut = false;
274
379
  let timeoutId;
275
- const proc = spawn("sh", ["-c", command], {
380
+ const proc = spawn(file, args, {
276
381
  cwd: options.cwd,
277
382
  env: { ...process.env, ...options.env },
278
383
  stdio: ["ignore", "pipe", "pipe"],
@@ -305,7 +410,7 @@ var init_runner = __esm({
305
410
  proc.on("close", (code) => {
306
411
  if (timeoutId)
307
412
  clearTimeout(timeoutId);
308
- resolve5({
413
+ resolve10({
309
414
  exitCode: code ?? 1,
310
415
  output,
311
416
  timedOut
@@ -314,7 +419,7 @@ var init_runner = __esm({
314
419
  proc.on("error", () => {
315
420
  if (timeoutId)
316
421
  clearTimeout(timeoutId);
317
- resolve5({ exitCode: 1, output, timedOut });
422
+ resolve10({ exitCode: 1, output, timedOut });
318
423
  });
319
424
  });
320
425
  }
@@ -831,19 +936,19 @@ function envWithoutHarness(env = process.env) {
831
936
  return out;
832
937
  }
833
938
  function runDoctor(cwBin) {
834
- return new Promise((resolve5) => {
939
+ return new Promise((resolve10) => {
835
940
  execFile(cwBin, ["doctor", "--json"], { timeout: TIMEOUT_MS, env: envWithoutHarness(), maxBuffer: 10 * 1024 * 1024 }, (err, stdout) => {
836
941
  if (err)
837
- return resolve5({ available: false, reason: err.message });
942
+ return resolve10({ available: false, reason: err.message });
838
943
  let parsed;
839
944
  try {
840
945
  parsed = JSON.parse(stdout);
841
946
  } catch {
842
- return resolve5({ available: false, reason: "cw doctor --json did not print JSON" });
947
+ return resolve10({ available: false, reason: "cw doctor --json did not print JSON" });
843
948
  }
844
949
  if (parsed.schema !== 1)
845
- return resolve5({ available: false, reason: `unsupported doctor schema ${String(parsed.schema)}` });
846
- resolve5({ available: true, doctor: parsed });
950
+ return resolve10({ available: false, reason: `unsupported doctor schema ${String(parsed.schema)}` });
951
+ resolve10({ available: true, doctor: parsed });
847
952
  });
848
953
  });
849
954
  }
@@ -948,14 +1053,14 @@ function closeWarningsFor(input) {
948
1053
  return warnings;
949
1054
  }
950
1055
  function createRunner(env, timeoutMs = COMMAND_TIMEOUT_MS) {
951
- return (bin, args, cwd, input) => new Promise((resolve5) => {
1056
+ return (bin, args, cwd, input) => new Promise((resolve10) => {
952
1057
  const child = execFile2(bin, args, { cwd, env, timeout: timeoutMs, maxBuffer: 5 * 1024 * 1024 }, (err, stdout, stderr) => {
953
1058
  if (!err)
954
- return resolve5({ code: 0, stdout: String(stdout), stderr: String(stderr) });
1059
+ return resolve10({ code: 0, stdout: String(stdout), stderr: String(stderr) });
955
1060
  const { code } = err;
956
1061
  if (code === "ENOENT")
957
- return resolve5({ code: 127, stdout: "", stderr: "ENOENT" });
958
- resolve5({ code: typeof code === "number" ? code : 1, stdout: String(stdout), stderr: String(stderr) || err.message });
1062
+ return resolve10({ code: 127, stdout: "", stderr: "ENOENT" });
1063
+ resolve10({ code: typeof code === "number" ? code : 1, stdout: String(stdout), stderr: String(stderr) || err.message });
959
1064
  });
960
1065
  if (input !== void 0) {
961
1066
  child.stdin?.on("error", () => {
@@ -976,11 +1081,11 @@ function isCwLink(worktree, porcelainLine) {
976
1081
  return false;
977
1082
  }
978
1083
  }
979
- async function readGitSnapshot(run, worktree) {
980
- const head = await run("git", ["rev-parse", "--abbrev-ref", "HEAD"], worktree);
1084
+ async function readGitSnapshot(run2, worktree) {
1085
+ const head = await run2("git", ["rev-parse", "--abbrev-ref", "HEAD"], worktree);
981
1086
  if (head.code !== 0)
982
1087
  throw new GitReadError(head.stderr.trim() || "git rev-parse failed");
983
- const status = await run("git", ["status", "--porcelain", "--untracked-files=all"], worktree);
1088
+ const status = await run2("git", ["status", "--porcelain", "--untracked-files=all"], worktree);
984
1089
  if (status.code !== 0)
985
1090
  throw new GitReadError(status.stderr.trim() || "git status failed");
986
1091
  const branchName = head.stdout.trim();
@@ -989,14 +1094,14 @@ async function readGitSnapshot(run, worktree) {
989
1094
  let unpushed = null;
990
1095
  if (branch) {
991
1096
  const remoteRef = `refs/remotes/origin/${branch}`;
992
- const verify = await run("git", ["rev-parse", "--verify", "--quiet", remoteRef], worktree);
1097
+ const verify = await run2("git", ["rev-parse", "--verify", "--quiet", remoteRef], worktree);
993
1098
  if (verify.code === 0) {
994
1099
  upstream = `origin/${branch}`;
995
- const count = await run("git", ["rev-list", "--count", `${remoteRef}..HEAD`], worktree);
1100
+ const count = await run2("git", ["rev-list", "--count", `${remoteRef}..HEAD`], worktree);
996
1101
  unpushed = count.code === 0 ? Number(count.stdout.trim()) : null;
997
1102
  }
998
1103
  }
999
- const remote = await run("git", ["remote", "get-url", "origin"], worktree);
1104
+ const remote = await run2("git", ["remote", "get-url", "origin"], worktree);
1000
1105
  return {
1001
1106
  branch,
1002
1107
  uncommitted: lines(status.stdout).filter((line) => !isCwLink(worktree, line)).length,
@@ -1005,28 +1110,28 @@ async function readGitSnapshot(run, worktree) {
1005
1110
  repo: remote.code === 0 ? parseGitHubRemote(remote.stdout) : null
1006
1111
  };
1007
1112
  }
1008
- async function resolveBase(run, cwd, candidates) {
1113
+ async function resolveBase(run2, cwd, candidates) {
1009
1114
  for (const candidate of candidates) {
1010
1115
  if (!candidate)
1011
1116
  continue;
1012
1117
  let ref = candidate;
1013
1118
  if (candidate === "origin/HEAD") {
1014
- const head = await run("git", ["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"], cwd);
1119
+ const head = await run2("git", ["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"], cwd);
1015
1120
  if (head.code !== 0)
1016
1121
  continue;
1017
1122
  ref = head.stdout.trim().replace(/^refs\/remotes\//, "");
1018
1123
  }
1019
- const verify = await run("git", ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], cwd);
1124
+ const verify = await run2("git", ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], cwd);
1020
1125
  if (verify.code === 0)
1021
1126
  return ref;
1022
1127
  }
1023
1128
  return null;
1024
1129
  }
1025
- async function readBaseCounts(run, cwd, base) {
1130
+ async function readBaseCounts(run2, cwd, base) {
1026
1131
  if (!base)
1027
1132
  return { commits: null, diff: null };
1028
- const count = await run("git", ["rev-list", "--count", `${base}..HEAD`], cwd);
1029
- const stat = await run("git", ["diff", "--shortstat", base], cwd);
1133
+ const count = await run2("git", ["rev-list", "--count", `${base}..HEAD`], cwd);
1134
+ const stat = await run2("git", ["diff", "--shortstat", base], cwd);
1030
1135
  return {
1031
1136
  commits: count.code === 0 ? Number(count.stdout.trim()) : null,
1032
1137
  diff: stat.code === 0 ? parseShortstat(stat.stdout) : null
@@ -1051,8 +1156,8 @@ function ghUnavailable(result2) {
1051
1156
  const firstLine = result2.stderr.split("\n").map((line) => line.trim()).find((line) => line.length > 0);
1052
1157
  return { status: "unavailable", reason: firstLine ?? "gh failed" };
1053
1158
  }
1054
- async function readPullRequestForBranch(run, cwd, branch) {
1055
- const result2 = await run("gh", ["pr", "list", "--head", branch, "--state", "all", "--limit", "1", "--json", PR_FIELDS], cwd);
1159
+ async function readPullRequestForBranch(run2, cwd, branch) {
1160
+ const result2 = await run2("gh", ["pr", "list", "--head", branch, "--state", "all", "--limit", "1", "--json", PR_FIELDS], cwd);
1056
1161
  if (result2.code !== 0)
1057
1162
  return ghUnavailable(result2);
1058
1163
  try {
@@ -1064,8 +1169,8 @@ async function readPullRequestForBranch(run, cwd, branch) {
1064
1169
  return UNEXPECTED;
1065
1170
  }
1066
1171
  }
1067
- async function readPullRequestByNumber(run, cwd, number) {
1068
- const result2 = await run("gh", ["pr", "view", number, "--json", PR_FIELDS], cwd);
1172
+ async function readPullRequestByNumber(run2, cwd, number) {
1173
+ const result2 = await run2("gh", ["pr", "view", number, "--json", PR_FIELDS], cwd);
1069
1174
  if (result2.code !== 0)
1070
1175
  return ghUnavailable(result2);
1071
1176
  try {
@@ -1100,8 +1205,8 @@ async function buildReviewSessionState(session, projectPath, deps) {
1100
1205
  const github = githubLink({ repo, kind: "review", prNumber, pr, branch: null, base: null, upstream: null, commits: null, uncommitted: 0 });
1101
1206
  return { ...idleState("none"), pr, github };
1102
1207
  }
1103
- async function isAncestor(run, cwd, ancestor, descendant) {
1104
- return (await run("git", ["merge-base", "--is-ancestor", ancestor, descendant], cwd)).code === 0;
1208
+ async function isAncestor(run2, cwd, ancestor, descendant) {
1209
+ return (await run2("git", ["merge-base", "--is-ancestor", ancestor, descendant], cwd)).code === 0;
1105
1210
  }
1106
1211
  async function buildTaskReviewState(session, projectPath, deps) {
1107
1212
  if (session.type === "review")
@@ -1155,7 +1260,7 @@ function createLimiter(max) {
1155
1260
  const waiting = [];
1156
1261
  return async (fn) => {
1157
1262
  if (active >= max)
1158
- await new Promise((resolve5) => waiting.push(resolve5));
1263
+ await new Promise((resolve10) => waiting.push(resolve10));
1159
1264
  else
1160
1265
  active++;
1161
1266
  try {
@@ -1355,7 +1460,7 @@ function mapCodexUsage(payload) {
1355
1460
  });
1356
1461
  }
1357
1462
  function callCodexAppServer(bin, codexHome, timeoutMs = TIMEOUT_MS3) {
1358
- return new Promise((resolve5, reject) => {
1463
+ return new Promise((resolve10, reject) => {
1359
1464
  const child = spawn2(bin, ["app-server"], { env: { ...CHILD_ENV, CODEX_HOME: codexHome }, stdio: ["pipe", "pipe", "ignore"] });
1360
1465
  let buffer = "";
1361
1466
  let settled = false;
@@ -1375,7 +1480,7 @@ function callCodexAppServer(bin, codexHome, timeoutMs = TIMEOUT_MS3) {
1375
1480
  const done = (value) => {
1376
1481
  if (!settled) {
1377
1482
  stop();
1378
- resolve5(value);
1483
+ resolve10(value);
1379
1484
  }
1380
1485
  };
1381
1486
  const timer = setTimeout(() => fail(new Error(`codex app-server did not answer in ${timeoutMs / 1e3} s`)), timeoutMs);
@@ -1642,7 +1747,7 @@ var init_login_manager = __esm({
1642
1747
  // ../core/dist/api-key-login.js
1643
1748
  import { spawn as spawn4 } from "node:child_process";
1644
1749
  function importApiKey(cwBin, account, harness, apiKey) {
1645
- return new Promise((resolve5) => {
1750
+ return new Promise((resolve10) => {
1646
1751
  const redact = (text) => text.split(apiKey).join("***").trim();
1647
1752
  const child = spawn4(cwBin, ["account", "login", account, "--harness", harness, "--with-api-key", "-"], {
1648
1753
  env: envWithoutHarness(),
@@ -1659,11 +1764,11 @@ function importApiKey(cwBin, account, harness, apiKey) {
1659
1764
  const timer = setTimeout(() => child.kill(), TIMEOUT_MS4);
1660
1765
  child.on("error", (err) => {
1661
1766
  clearTimeout(timer);
1662
- resolve5({ ok: false, error: redact(err.message) });
1767
+ resolve10({ ok: false, error: redact(err.message) });
1663
1768
  });
1664
1769
  child.on("close", (code) => {
1665
1770
  clearTimeout(timer);
1666
- resolve5(code === 0 ? { ok: true } : { ok: false, error: redact(output) || `cw exited with ${String(code)}` });
1771
+ resolve10(code === 0 ? { ok: true } : { ok: false, error: redact(output) || `cw exited with ${String(code)}` });
1667
1772
  });
1668
1773
  child.stdin.end(`${apiKey}
1669
1774
  `);
@@ -1695,12 +1800,12 @@ function detectEditors(probe) {
1695
1800
  return found;
1696
1801
  }
1697
1802
  function openInEditor(editor, dir) {
1698
- return new Promise((resolve5, reject) => {
1803
+ return new Promise((resolve10, reject) => {
1699
1804
  const child = spawn5(editor.bin, [...editor.args, dir], { detached: true, stdio: "ignore" });
1700
1805
  child.once("error", reject);
1701
1806
  child.once("spawn", () => {
1702
1807
  child.unref();
1703
- resolve5();
1808
+ resolve10();
1704
1809
  });
1705
1810
  });
1706
1811
  }
@@ -1779,7 +1884,7 @@ function cwRoutes(reader, options = {}) {
1779
1884
  const app = new Hono();
1780
1885
  const cwBin = resolveCwBin(reader.cwHome);
1781
1886
  const logins = options.loginManager ?? new LoginManager(cwBin);
1782
- const run = options.runner ?? runCommand;
1887
+ const run2 = options.runner ?? runCommand;
1783
1888
  const localOnly = options.localOnly ?? true;
1784
1889
  const editors = options.editors ?? detectEditors(systemProbe);
1785
1890
  const cwDoneTimeoutMs = options.cwDoneTimeoutMs ?? CW_DONE_TIMEOUT_MS;
@@ -1788,10 +1893,28 @@ function cwRoutes(reader, options = {}) {
1788
1893
  const reviewCache = /* @__PURE__ */ new Map();
1789
1894
  const knownAccount = (name) => ACCOUNT_NAME_RE.test(name) && reader.getAccounts().includes(name);
1790
1895
  const doctor = createDoctorClient(cwBin);
1896
+ let cells = null;
1897
+ const noteHarnesses = (accounts) => {
1898
+ const next = /* @__PURE__ */ new Map();
1899
+ for (const a of accounts)
1900
+ for (const h of a.harnesses)
1901
+ next.set(`${a.name}\0${h.harness}`, h.status);
1902
+ if (cells && options.events) {
1903
+ for (const [key, to] of next) {
1904
+ const from = cells.get(key);
1905
+ if (from === void 0 || from === to)
1906
+ continue;
1907
+ const [account, harness] = key.split("\0");
1908
+ options.events.emit("harness.changed", { account, harness, from, to });
1909
+ }
1910
+ }
1911
+ cells = next;
1912
+ };
1791
1913
  app.get("/harnesses", async (c) => {
1792
1914
  const result2 = await doctor.get(c.req.query("fresh") === "1");
1793
1915
  if (!result2.available)
1794
1916
  return c.json(result2);
1917
+ noteHarnesses(result2.doctor.accounts);
1795
1918
  const capabilities = Object.fromEntries(result2.doctor.harnesses.map((h) => [h.name, [...HARNESS_CAPABILITIES[h.name] ?? []]]));
1796
1919
  return c.json({ ...result2, capabilities, contextTokens: readContextTokens(reader.cwHome) });
1797
1920
  });
@@ -1877,8 +2000,8 @@ function cwRoutes(reader, options = {}) {
1877
2000
  return c.json({ ok: false, error: `Account "${name}" not found` }, 404);
1878
2001
  }
1879
2002
  try {
1880
- const { rmSync: rmSync3 } = await import("node:fs");
1881
- rmSync3(accountDir, { recursive: true, force: true });
2003
+ const { rmSync: rmSync4 } = await import("node:fs");
2004
+ rmSync4(accountDir, { recursive: true, force: true });
1882
2005
  return c.json({ ok: true });
1883
2006
  } catch (err) {
1884
2007
  const message = err instanceof Error ? err.message : "Unknown error";
@@ -1947,7 +2070,7 @@ function cwRoutes(reader, options = {}) {
1947
2070
  return c.json({ error: "Session not found" }, 404);
1948
2071
  if ("empty" in result2)
1949
2072
  return c.json({ output: "" });
1950
- const status = await run("git", ["status", "--short"], result2.session.worktree);
2073
+ const status = await run2("git", ["status", "--short"], result2.session.worktree);
1951
2074
  return c.json({ output: status.code === 0 ? status.stdout : "" });
1952
2075
  });
1953
2076
  app.get("/git/log/:project/:sessionDir", async (c) => {
@@ -1956,7 +2079,7 @@ function cwRoutes(reader, options = {}) {
1956
2079
  return c.json({ error: "Session not found" }, 404);
1957
2080
  if ("empty" in result2)
1958
2081
  return c.json({ output: "" });
1959
- const log = await run("git", ["log", "--oneline", "-20"], result2.session.worktree);
2082
+ const log = await run2("git", ["log", "--oneline", "-20"], result2.session.worktree);
1960
2083
  return c.json({ output: log.code === 0 ? log.stdout : "" });
1961
2084
  });
1962
2085
  app.get("/git/branch/:project/:sessionDir", async (c) => {
@@ -1965,7 +2088,7 @@ function cwRoutes(reader, options = {}) {
1965
2088
  return c.json({ error: "Session not found" }, 404);
1966
2089
  if ("empty" in result2)
1967
2090
  return c.json({ branch: "" });
1968
- const head = await run("git", ["rev-parse", "--abbrev-ref", "HEAD"], result2.session.worktree);
2091
+ const head = await run2("git", ["rev-parse", "--abbrev-ref", "HEAD"], result2.session.worktree);
1969
2092
  return c.json({ branch: head.code === 0 ? head.stdout.trim() : "" });
1970
2093
  });
1971
2094
  app.get("/git/diff/:project/:sessionDir", async (c) => {
@@ -1975,10 +2098,10 @@ function cwRoutes(reader, options = {}) {
1975
2098
  if ("empty" in result2)
1976
2099
  return c.json({ output: "" });
1977
2100
  const worktree = result2.session.worktree;
1978
- const base = await resolveBase(run, worktree, [result2.session.base_branch, "origin/HEAD", "origin/main"]);
2101
+ const base = await resolveBase(run2, worktree, [result2.session.base_branch, "origin/HEAD", "origin/main"]);
1979
2102
  if (!base)
1980
2103
  return c.json({ output: "" });
1981
- const diff = await run("git", ["diff", "--stat", base], worktree);
2104
+ const diff = await run2("git", ["diff", "--stat", base], worktree);
1982
2105
  return c.json({ output: diff.code === 0 ? diff.stdout : "" });
1983
2106
  });
1984
2107
  app.get("/review-state/:project/:sessionDir", async (c) => {
@@ -1993,7 +2116,7 @@ function cwRoutes(reader, options = {}) {
1993
2116
  return c.json(await cached.value);
1994
2117
  }
1995
2118
  const projectPath = reader.getProjects()[project]?.path ?? null;
1996
- const value = buildTaskReviewState(session, projectPath, { run, limitGh, exists: existsSync5 });
2119
+ const value = buildTaskReviewState(session, projectPath, { run: run2, limitGh, exists: existsSync5 });
1997
2120
  reviewCache.set(key, { at: Date.now(), value });
1998
2121
  value.catch(() => reviewCache.delete(key));
1999
2122
  return c.json(await value);
@@ -2280,8 +2403,20 @@ function cwRoutes(reader, options = {}) {
2280
2403
  const args = type === "review" ? ["review", project, task, "--done"] : type === "loop" ? ["loop", project, task, "--done"] : ["work", project, task, "--done"];
2281
2404
  reviewCache.delete(`${project}::${sessionDirName}`);
2282
2405
  const result2 = await runCw(cwBin, args, cwDoneTimeoutMs);
2283
- if (result2.code === 0)
2406
+ if (result2.code === 0) {
2407
+ const session = reader.getSession(project, sessionDirName);
2408
+ options.events?.emit("task.done", {
2409
+ project,
2410
+ sessionDir: sessionDirName,
2411
+ type: session?.type ?? type,
2412
+ account: session?.account,
2413
+ harness: session?.harness,
2414
+ provider: session?.provider,
2415
+ model: session?.model,
2416
+ command: args[0]
2417
+ });
2284
2418
  return c.json({ ok: true });
2419
+ }
2285
2420
  const output = tailOutput(`${result2.stdout}
2286
2421
  ${result2.stderr}`);
2287
2422
  const error = result2.timedOut ? [cwDoneTimeoutMessage(cwDoneTimeoutMs), output].filter(Boolean).join("\n") : output || "cw --done failed";
@@ -2420,6 +2555,7 @@ ${result2.stderr}`);
2420
2555
  args.push("--type", type.trim());
2421
2556
  try {
2422
2557
  await execFileAsync2(cwBin, args, { encoding: "utf-8", timeout: 3e4, env: envWithoutHarness() });
2558
+ options.events?.emit("project.registered", { project: projectName, path: projectPath });
2423
2559
  return c.json({ ok: true, project: projectName });
2424
2560
  } catch (err) {
2425
2561
  const message = err instanceof Error ? err.message : "Unknown error";
@@ -2467,12 +2603,12 @@ function normalizeRepo(value) {
2467
2603
  const m = value.trim().match(/^(?:git@github\.com:|(?:https?|ssh|git):\/\/(?:[^@/]+@)?github\.com\/)?([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i);
2468
2604
  return m ? `${m[1]}/${m[2]}`.toLowerCase() : void 0;
2469
2605
  }
2470
- function createRemoteLookup(run) {
2606
+ function createRemoteLookup(run2) {
2471
2607
  const cache = /* @__PURE__ */ new Map();
2472
2608
  return (projectPath) => {
2473
2609
  let hit = cache.get(projectPath);
2474
2610
  if (!hit) {
2475
- hit = run("git", ["remote", "get-url", "origin"], projectPath).then((r) => r.code === 0 && r.stdout.trim() || null).catch(() => null);
2611
+ hit = run2("git", ["remote", "get-url", "origin"], projectPath).then((r) => r.code === 0 && r.stdout.trim() || null).catch(() => null);
2476
2612
  cache.set(projectPath, hit);
2477
2613
  }
2478
2614
  return hit;
@@ -2683,9 +2819,9 @@ function skillRoutes(reader, options = {}) {
2683
2819
  busy.add(configDir);
2684
2820
  try {
2685
2821
  const { CLAUDE_CONFIG_DIR: _ignored, ...base } = envWithoutHarness();
2686
- const run = runnerFor(scope === "global" ? base : { ...base, CLAUDE_CONFIG_DIR: configDir });
2822
+ const run2 = runnerFor(scope === "global" ? base : { ...base, CLAUDE_CONFIG_DIR: configDir });
2687
2823
  for (const args of commands) {
2688
- const result2 = await run("claude", args, configDir);
2824
+ const result2 = await run2("claude", args, configDir);
2689
2825
  if (result2.code !== 0)
2690
2826
  return { error: `${failure}: ${commandFailure(result2)}`, status: 500 };
2691
2827
  }
@@ -2896,8 +3032,8 @@ function skillRoutes(reader, options = {}) {
2896
3032
  const args = ["--yes", "skills", "add", repo, "--skill", skill, "--agent", "claude-code", "--yes", "--json"];
2897
3033
  if (scope !== "project")
2898
3034
  args.push("--global");
2899
- const run = runnerFor({ ...envWithoutHarness(), CLAUDE_CONFIG_DIR: configDir });
2900
- const result2 = await run("npx", args, dirname2(configDir));
3035
+ const run2 = runnerFor({ ...envWithoutHarness(), CLAUDE_CONFIG_DIR: configDir });
3036
+ const result2 = await run2("npx", args, dirname2(configDir));
2901
3037
  if (result2.code !== 0) {
2902
3038
  return c.json({ error: `Failed to install skill: ${installFailure(result2)}` }, 500);
2903
3039
  }
@@ -3079,6 +3215,8 @@ var init_pty_manager = __esm({
3079
3215
  states;
3080
3216
  sessions = /* @__PURE__ */ new Map();
3081
3217
  cleanupTimer = null;
3218
+ // told when a session's agent starts and when its process exits
3219
+ onLifecycle;
3082
3220
  constructor(states = null) {
3083
3221
  this.states = states;
3084
3222
  this.cleanupTimer = setInterval(() => this.cleanup(), CLEANUP_INTERVAL_MS);
@@ -3091,12 +3229,12 @@ var init_pty_manager = __esm({
3091
3229
  const existing = this.sessions.get(key);
3092
3230
  if (existing)
3093
3231
  return existing;
3094
- const shell = process.env.SHELL || "/bin/zsh";
3232
+ const shell2 = process.env.SHELL || "/bin/zsh";
3095
3233
  const { command, env } = buildLaunch(session, options.isNew ?? false);
3096
3234
  const cwd = session.worktree && existsSync8(session.worktree) ? session.worktree : session.type === "general" || session.type === "create" || session.type === "login" ? process.env.HOME ?? process.cwd() : process.cwd();
3097
3235
  let ptyProcess;
3098
3236
  try {
3099
- ptyProcess = pty2.spawn(shell, ["-c", command], {
3237
+ ptyProcess = pty2.spawn(shell2, ["-c", command], {
3100
3238
  name: "xterm-256color",
3101
3239
  cols: 120,
3102
3240
  rows: 40,
@@ -3144,8 +3282,10 @@ var init_pty_manager = __esm({
3144
3282
  }
3145
3283
  }
3146
3284
  this.sessions.delete(key);
3285
+ this.onLifecycle?.("ended", session);
3147
3286
  });
3148
3287
  this.sessions.set(key, ptySession);
3288
+ this.onLifecycle?.("started", session);
3149
3289
  return ptySession;
3150
3290
  }
3151
3291
  attach(sessionId, client) {
@@ -3369,7 +3509,7 @@ var init_terminal_screen = __esm({
3369
3509
  }
3370
3510
  // rows oldest first, scrollback included, without the blank rows under the last one written
3371
3511
  read() {
3372
- return new Promise((resolve5) => this.term.write("", () => {
3512
+ return new Promise((resolve10) => this.term.write("", () => {
3373
3513
  const buffer = this.term.buffer.active;
3374
3514
  const rows = [];
3375
3515
  for (let y = 0; y < buffer.length; y++) {
@@ -3385,7 +3525,7 @@ var init_terminal_screen = __esm({
3385
3525
  const trimmed = rows.map((r) => r.trimEnd());
3386
3526
  while (trimmed.length && !trimmed[trimmed.length - 1])
3387
3527
  trimmed.pop();
3388
- resolve5(trimmed.join("\n"));
3528
+ resolve10(trimmed.join("\n"));
3389
3529
  }));
3390
3530
  }
3391
3531
  dispose() {
@@ -4075,7 +4215,7 @@ function failureMessage2(output) {
4075
4215
  async function ensureCw(options) {
4076
4216
  const { cwHome, bundleDir } = options;
4077
4217
  const env = options.env ?? process.env;
4078
- const run = options.run ?? runInstall;
4218
+ const run2 = options.run ?? runInstall;
4079
4219
  const bin = join12(cwHome, "bin", "cw");
4080
4220
  const bundle = readCwBundle(bundleDir);
4081
4221
  const installed = existsSync11(bin) ? { version: readCwVersion(bin), sha256: sha256Of(bin) } : null;
@@ -4088,7 +4228,7 @@ async function ensureCw(options) {
4088
4228
  });
4089
4229
  if (decision.action === "skip" || !bundle)
4090
4230
  return { action: "skipped", message: decision.reason };
4091
- const { code, output } = await run(join12(bundle.dir, "install.sh"), ["--no-shell"], { ...env, CW_HOME: cwHome });
4231
+ const { code, output } = await run2(join12(bundle.dir, "install.sh"), ["--no-shell"], { ...env, CW_HOME: cwHome });
4092
4232
  if (code !== 0 || !existsSync11(bin))
4093
4233
  return { action: "failed", message: failureMessage2(output) };
4094
4234
  const marker = { version: bundle.version, ref: bundle.ref, sha256: sha256Of(bin) };
@@ -4107,13 +4247,13 @@ var init_cw_install = __esm({
4107
4247
  INSTALL_TIMEOUT_MS2 = 12e4;
4108
4248
  ANSI_RE3 = /\u001b\[[0-9;?]*[A-Za-z]/g;
4109
4249
  sha256Of = (file) => createHash2("sha256").update(readFileSync9(file)).digest("hex");
4110
- runInstall = (script, args, env) => new Promise((resolve5) => {
4250
+ runInstall = (script, args, env) => new Promise((resolve10) => {
4111
4251
  execFile5("bash", [script, ...args], { env, timeout: INSTALL_TIMEOUT_MS2, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
4112
4252
  const output = `${String(stdout)}${String(stderr)}`;
4113
4253
  if (!err)
4114
- return resolve5({ code: 0, output });
4254
+ return resolve10({ code: 0, output });
4115
4255
  const code = err.code;
4116
- resolve5({ code: typeof code === "number" ? code : 1, output: output || err.message });
4256
+ resolve10({ code: typeof code === "number" ? code : 1, output: output || err.message });
4117
4257
  });
4118
4258
  });
4119
4259
  }
@@ -4138,12 +4278,12 @@ function rememberPrompt(text) {
4138
4278
  return `Remember this with kioku: ${text.replace(/\s+/g, " ").trim()}`;
4139
4279
  }
4140
4280
  function createTerminalRunner(env, timeoutMs) {
4141
- return (bin, args, cwd) => new Promise((resolve5) => {
4281
+ return (bin, args, cwd) => new Promise((resolve10) => {
4142
4282
  let proc;
4143
4283
  try {
4144
4284
  proc = pty3.spawn(bin, args, { name: "xterm-256color", cols: 400, rows: 40, cwd, env });
4145
4285
  } catch {
4146
- return resolve5({ code: 127, stdout: "", stderr: "ENOENT" });
4286
+ return resolve10({ code: 127, stdout: "", stderr: "ENOENT" });
4147
4287
  }
4148
4288
  let output = "";
4149
4289
  const timer = setTimeout(() => proc.kill(), timeoutMs);
@@ -4153,7 +4293,7 @@ function createTerminalRunner(env, timeoutMs) {
4153
4293
  proc.onExit(({ exitCode }) => {
4154
4294
  clearTimeout(timer);
4155
4295
  const json = stripAnsi(output).split(/\r?\n/).reverse().map((line) => line.slice(line.indexOf("{")).trim()).find((line) => parseJson(line) !== null);
4156
- resolve5({ code: exitCode, stdout: json ?? "", stderr: output });
4296
+ resolve10({ code: exitCode, stdout: json ?? "", stderr: output });
4157
4297
  });
4158
4298
  });
4159
4299
  }
@@ -4355,15 +4495,15 @@ var init_kioku = __esm({
4355
4495
  this.snapshot.at = -Infinity;
4356
4496
  }
4357
4497
  // runs a verb that writes; fail turns kioku's refusal into a 400 with its message
4358
- async invoke(args, cwd, run, input) {
4359
- const result2 = await run(this.bin, args, cwd, input);
4498
+ async invoke(args, cwd, run2, input) {
4499
+ const result2 = await run2(this.bin, args, cwd, input);
4360
4500
  if (result2.code === 127)
4361
4501
  throw new KiokuError(NOT_INSTALLED, 404);
4362
4502
  const out = parseJson(result2.stdout);
4363
4503
  return { out, ok: result2.code === 0 && out !== null && !out.error, fail: (fallback) => new KiokuError(out?.error?.message ?? (tailOutput(result2.stderr, 1) || fallback), 400) };
4364
4504
  }
4365
- async change(args, cwd, run = this.write) {
4366
- const { out, ok, fail } = await this.invoke([...args, "--json"], cwd, run);
4505
+ async change(args, cwd, run2 = this.write) {
4506
+ const { out, ok, fail } = await this.invoke([...args, "--json"], cwd, run2);
4367
4507
  if (!ok || !out)
4368
4508
  throw fail(`kioku ${args.slice(0, 2).join(" ")} failed`);
4369
4509
  this.expire();
@@ -4437,7 +4577,7 @@ var init_kioku = __esm({
4437
4577
  return (await this.viewer).address;
4438
4578
  }
4439
4579
  startViewer() {
4440
- const started = new Promise((resolve5, reject) => {
4580
+ const started = new Promise((resolve10, reject) => {
4441
4581
  const child = spawn7(this.bin, ["web", "--json", "--no-open"], { cwd: homedir5(), stdio: ["ignore", "pipe", "pipe"] });
4442
4582
  const lines2 = createInterface({ input: child.stdout });
4443
4583
  let stderr = "";
@@ -4464,7 +4604,7 @@ var init_kioku = __esm({
4464
4604
  if (settled || event?.event !== "listening" || !event.address?.startsWith("http://127.0.0.1:"))
4465
4605
  return;
4466
4606
  finish();
4467
- resolve5({ child, address: event.address });
4607
+ resolve10({ child, address: event.address });
4468
4608
  });
4469
4609
  child.on("error", (err) => {
4470
4610
  const missing = err.code === "ENOENT";
@@ -4563,226 +4703,3506 @@ var init_kioku_routes = __esm({
4563
4703
  }
4564
4704
  });
4565
4705
 
4566
- // ../core/dist/server.js
4567
- import { Hono as Hono5 } from "hono";
4568
- import { cors } from "hono/cors";
4569
- import { join as join14, basename as basename3, resolve as resolve4 } from "node:path";
4570
- import { readdirSync as readdirSync7, existsSync as existsSync13 } from "node:fs";
4571
- function createForgeServer(options) {
4572
- const { dataDir, db: externalDb, authToken, localOnly = true } = options;
4573
- const dbPath = join14(dataDir, "forge.db");
4574
- const modulesDir = join14(dataDir, "modules");
4575
- const db = externalDb ?? new ForgeDB(dbPath);
4576
- const loader = new ModuleLoader(modulesDir, options.bundledModulesDir);
4577
- const runner = new ActionRunner();
4578
- loader.discover();
4579
- const app = new Hono5();
4580
- app.use("*", localOnly ? localOriginGuard() : cors());
4581
- if (authToken) {
4582
- app.use("/api/*", bearerAuth(authToken));
4706
+ // ../sdk/dist/define.js
4707
+ function isShellExecutor(run2) {
4708
+ return typeof run2 === "object" && run2 !== null && run2.kind === "shell";
4709
+ }
4710
+ var SDK_VERSION, MODULE_ID_RE;
4711
+ var init_define = __esm({
4712
+ "../sdk/dist/define.js"() {
4713
+ "use strict";
4714
+ SDK_VERSION = "1.0.0";
4715
+ MODULE_ID_RE = /^[a-z][a-z0-9-]{1,31}$/;
4583
4716
  }
4584
- const cwReader = new CWReader(options.cwDir);
4585
- const loginManager = new LoginManager(resolveCwBin(cwReader.cwHome));
4586
- app.route("/api/cw", cwRoutes(cwReader, { loginManager, localOnly }));
4587
- app.route("/api/skills", skillRoutes(cwReader, { backupDir: join14(dataDir, "skill-backups") }));
4588
- const { remote, shadow, warning } = remoteClassifierFromEnv();
4589
- if (warning)
4590
- console.warn(`[state] ${warning}`);
4591
- const logPath = process.env.FORGE_STATE_LOG;
4592
- if (logPath && !remote)
4593
- console.warn("[state] FORGE_STATE_LOG only records remote classifier calls; set FORGE_STATE_CLASSIFIER=jev");
4594
- const onRemote = logPath && remote ? createStateLog(logPath, (err) => console.warn(`[state] could not write ${logPath}: ${err.message}`)) : void 0;
4595
- let lastStateError = "";
4596
- const states = new StateTracker({
4597
- remote,
4598
- shadow,
4599
- onRemote,
4600
- onError: (err) => {
4601
- if (err.message !== lastStateError)
4602
- console.warn(`[state] ${remote?.name ?? "remote"} classifier failed, using local rules: ${err.message}`);
4603
- lastStateError = err.message;
4604
- }
4605
- });
4606
- const ptyManager = new PTYManager(states);
4607
- const generalSessions = new GeneralSessions(join14(dataDir, "general-sessions.json"));
4608
- const terminalWss = createTerminalWss(ptyManager, cwReader, { localOnly, general: generalSessions });
4609
- app.route("/api/liveframe", liveframeRoutes());
4610
- const kioku = new Kioku({ projects: () => cwReader.getProjects() });
4611
- app.route("/api/kioku", kiokuRoutes(kioku, {
4612
- type: (project, sessionDir, text) => ptyManager.typeLine(project, sessionDir, text),
4613
- // kioku's plugin, and so its skill, exists only for Claude Code
4614
- canRemember: (project, sessionDir) => cwReader.getSession(project, sessionDir)?.harness === "claude"
4615
- }));
4616
- app.get("/api/cw/session-states", (c) => c.json({ classifier: states.remoteName ?? "local", shadow: states.isShadow, states: states.snapshot() }));
4617
- app.post("/api/cw/terminal/kill", async (c) => {
4618
- const { project, sessionDir } = await c.req.json();
4619
- const sessionId = `${project}::${sessionDir}`;
4620
- ptyManager.kill(sessionId);
4621
- generalSessions.forget(sessionId);
4622
- return c.json({ ok: true });
4623
- });
4624
- async function resolveAction(c) {
4625
- const moduleName = c.req.param("module");
4626
- const actionId = c.req.param("action");
4627
- const { projectId, cwProject, params } = await c.req.json();
4628
- const action = loader.getAction(moduleName, actionId);
4629
- if (!action) {
4630
- return c.json({ error: "Action not found" }, 404);
4631
- }
4632
- const checked = validateParams(action, params);
4633
- if ("error" in checked) {
4634
- return c.json({ error: checked.error }, 400);
4635
- }
4636
- let cwd;
4637
- if (cwProject !== void 0) {
4638
- const projects = cwReader.getProjects();
4639
- const path = Object.hasOwn(projects, cwProject) ? projects[cwProject]?.path : void 0;
4640
- if (!path)
4641
- return c.json({ error: `Unknown CW project: ${cwProject}` }, 400);
4642
- cwd = path;
4643
- } else {
4644
- cwd = (projectId ? db.getProject(projectId) : void 0)?.path ?? process.cwd();
4645
- }
4646
- const logId = db.logAction({
4647
- projectId: projectId ?? null,
4648
- moduleId: moduleName,
4649
- actionId,
4650
- command: action.command
4651
- });
4652
- return { action, cwd, logId, env: checked.env };
4717
+ });
4718
+
4719
+ // ../sdk/dist/errors.js
4720
+ var PermissionError;
4721
+ var init_errors = __esm({
4722
+ "../sdk/dist/errors.js"() {
4723
+ "use strict";
4724
+ PermissionError = class extends Error {
4725
+ permission;
4726
+ value;
4727
+ constructor(permission, value) {
4728
+ super(`permission ${permission} does not cover ${value}`);
4729
+ this.name = "PermissionError";
4730
+ this.permission = permission;
4731
+ this.value = value;
4732
+ }
4733
+ };
4653
4734
  }
4654
- app.get("/api/health", (c) => {
4655
- return c.json({
4656
- status: "ok",
4657
- version: options.version ?? null,
4658
- modules: loader.getLoadedCount()
4659
- });
4660
- });
4661
- app.get("/api/projects", (c) => {
4662
- return c.json(db.listProjects());
4663
- });
4664
- app.post("/api/projects", async (c) => {
4665
- const { name, path } = await c.req.json();
4666
- const id = db.addProject({ name, path });
4667
- const project = db.getProject(id);
4668
- return c.json(project, 201);
4669
- });
4670
- app.delete("/api/projects/:id", (c) => {
4671
- db.removeProject(c.req.param("id"));
4672
- return c.json({ ok: true });
4673
- });
4674
- app.get("/api/modules", (c) => {
4675
- const installed = db.listModules();
4676
- const loaded = loader.getLoaded();
4677
- return c.json(installed.map((m) => ({
4678
- ...m,
4679
- manifest: loaded.get(m.name) ?? null
4680
- })));
4681
- });
4682
- app.get("/api/modules/available", (c) => {
4683
- const manifests = loader.discover();
4684
- return c.json(manifests);
4685
- });
4686
- app.post("/api/actions/:module/:action", async (c) => {
4687
- const resolved = await resolveAction(c);
4688
- if (resolved instanceof Response)
4689
- return resolved;
4690
- const { action, cwd, logId, env } = resolved;
4691
- const result2 = await runner.exec(action.command, { cwd, env });
4692
- db.completeAction(logId, result2.exitCode);
4693
- return c.json({
4694
- logId,
4695
- exitCode: result2.exitCode,
4696
- output: result2.output,
4697
- timedOut: result2.timedOut
4698
- });
4699
- });
4700
- app.post("/api/actions/:module/:action/stream", async (c) => {
4701
- const resolved = await resolveAction(c);
4702
- if (resolved instanceof Response)
4703
- return resolved;
4704
- const { action, cwd, logId, env } = resolved;
4705
- return new Response(new ReadableStream({
4706
- async start(controller) {
4707
- const encoder = new TextEncoder();
4708
- const send = (event, data) => {
4709
- controller.enqueue(encoder.encode(`event: ${event}
4710
- data: ${JSON.stringify(data)}
4735
+ });
4711
4736
 
4712
- `));
4713
- };
4714
- send("start", { logId, command: action.command });
4715
- const result2 = await runner.exec(action.command, {
4716
- cwd,
4717
- env,
4718
- onData: (chunk) => send("output", { chunk })
4719
- });
4720
- db.completeAction(logId, result2.exitCode);
4721
- send("done", { exitCode: result2.exitCode, timedOut: result2.timedOut });
4722
- controller.close();
4737
+ // ../sdk/dist/index.js
4738
+ var init_dist = __esm({
4739
+ "../sdk/dist/index.js"() {
4740
+ "use strict";
4741
+ init_define();
4742
+ init_errors();
4743
+ }
4744
+ });
4745
+
4746
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js
4747
+ var require_constants = __commonJS({
4748
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js"(exports, module) {
4749
+ "use strict";
4750
+ var SEMVER_SPEC_VERSION = "2.0.0";
4751
+ var MAX_LENGTH = 256;
4752
+ var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */
4753
+ 9007199254740991;
4754
+ var MAX_SAFE_COMPONENT_LENGTH = 16;
4755
+ var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
4756
+ var RELEASE_TYPES = [
4757
+ "major",
4758
+ "premajor",
4759
+ "minor",
4760
+ "preminor",
4761
+ "patch",
4762
+ "prepatch",
4763
+ "prerelease"
4764
+ ];
4765
+ module.exports = {
4766
+ MAX_LENGTH,
4767
+ MAX_SAFE_COMPONENT_LENGTH,
4768
+ MAX_SAFE_BUILD_LENGTH,
4769
+ MAX_SAFE_INTEGER,
4770
+ RELEASE_TYPES,
4771
+ SEMVER_SPEC_VERSION,
4772
+ FLAG_INCLUDE_PRERELEASE: 1,
4773
+ FLAG_LOOSE: 2
4774
+ };
4775
+ }
4776
+ });
4777
+
4778
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/debug.js
4779
+ var require_debug = __commonJS({
4780
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/debug.js"(exports, module) {
4781
+ "use strict";
4782
+ var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {
4783
+ };
4784
+ module.exports = debug;
4785
+ }
4786
+ });
4787
+
4788
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/re.js
4789
+ var require_re = __commonJS({
4790
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/re.js"(exports, module) {
4791
+ "use strict";
4792
+ var {
4793
+ MAX_SAFE_COMPONENT_LENGTH,
4794
+ MAX_SAFE_BUILD_LENGTH,
4795
+ MAX_LENGTH
4796
+ } = require_constants();
4797
+ var debug = require_debug();
4798
+ exports = module.exports = {};
4799
+ var re = exports.re = [];
4800
+ var safeRe = exports.safeRe = [];
4801
+ var src = exports.src = [];
4802
+ var safeSrc = exports.safeSrc = [];
4803
+ var t = exports.t = {};
4804
+ var R = 0;
4805
+ var LETTERDASHNUMBER = "[a-zA-Z0-9-]";
4806
+ var safeRegexReplacements = [
4807
+ ["\\s", 1],
4808
+ ["\\d", MAX_LENGTH],
4809
+ [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
4810
+ ];
4811
+ var makeSafeRegex = (value) => {
4812
+ for (const [token, max] of safeRegexReplacements) {
4813
+ value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`);
4723
4814
  }
4724
- }), {
4725
- headers: {
4726
- "Content-Type": "text/event-stream",
4727
- "Cache-Control": "no-cache",
4728
- Connection: "keep-alive"
4815
+ return value;
4816
+ };
4817
+ var createToken = (name, value, isGlobal) => {
4818
+ const safe = makeSafeRegex(value);
4819
+ const index = R++;
4820
+ debug(name, index, value);
4821
+ t[name] = index;
4822
+ src[index] = value;
4823
+ safeSrc[index] = safe;
4824
+ re[index] = new RegExp(value, isGlobal ? "g" : void 0);
4825
+ safeRe[index] = new RegExp(safe, isGlobal ? "g" : void 0);
4826
+ };
4827
+ createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");
4828
+ createToken("NUMERICIDENTIFIERLOOSE", "\\d+");
4829
+ createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);
4830
+ createToken("MAINVERSION", `(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})`);
4831
+ createToken("MAINVERSIONLOOSE", `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})`);
4832
+ createToken("PRERELEASEIDENTIFIER", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIER]})`);
4833
+ createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIERLOOSE]})`);
4834
+ createToken("PRERELEASE", `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);
4835
+ createToken("PRERELEASELOOSE", `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);
4836
+ createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);
4837
+ createToken("BUILD", `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);
4838
+ createToken("FULLPLAIN", `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);
4839
+ createToken("FULL", `^${src[t.FULLPLAIN]}$`);
4840
+ createToken("LOOSEPLAIN", `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);
4841
+ createToken("LOOSE", `^${src[t.LOOSEPLAIN]}$`);
4842
+ createToken("GTLT", "((?:<|>)?=?)");
4843
+ createToken("XRANGEIDENTIFIERLOOSE", `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
4844
+ createToken("XRANGEIDENTIFIER", `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);
4845
+ createToken("XRANGEPLAIN", `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?)?)?`);
4846
+ createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?)?)?`);
4847
+ createToken("XRANGE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
4848
+ createToken("XRANGELOOSE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);
4849
+ createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
4850
+ createToken("COERCE", `${src[t.COERCEPLAIN]}(?:$|[^\\d])`);
4851
+ createToken("COERCEFULL", src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?(?:${src[t.BUILD]})?(?:$|[^\\d])`);
4852
+ createToken("COERCERTL", src[t.COERCE], true);
4853
+ createToken("COERCERTLFULL", src[t.COERCEFULL], true);
4854
+ createToken("LONETILDE", "(?:~>?)");
4855
+ createToken("TILDETRIM", `(\\s*)${src[t.LONETILDE]}\\s+`, true);
4856
+ exports.tildeTrimReplace = "$1~";
4857
+ createToken("TILDE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
4858
+ createToken("TILDELOOSE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);
4859
+ createToken("LONECARET", "(?:\\^)");
4860
+ createToken("CARETTRIM", `(\\s*)${src[t.LONECARET]}\\s+`, true);
4861
+ exports.caretTrimReplace = "$1^";
4862
+ createToken("CARET", `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
4863
+ createToken("CARETLOOSE", `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);
4864
+ createToken("COMPARATORLOOSE", `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
4865
+ createToken("COMPARATOR", `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);
4866
+ createToken("COMPARATORTRIM", `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
4867
+ exports.comparatorTrimReplace = "$1$2$3";
4868
+ createToken("HYPHENRANGE", `^\\s*(${src[t.XRANGEPLAIN]})\\s+-\\s+(${src[t.XRANGEPLAIN]})\\s*$`);
4869
+ createToken("HYPHENRANGELOOSE", `^\\s*(${src[t.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t.XRANGEPLAINLOOSE]})\\s*$`);
4870
+ createToken("STAR", "(<|>)?=?\\s*\\*");
4871
+ createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$");
4872
+ createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$");
4873
+ }
4874
+ });
4875
+
4876
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/parse-options.js
4877
+ var require_parse_options = __commonJS({
4878
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/parse-options.js"(exports, module) {
4879
+ "use strict";
4880
+ var looseOption = Object.freeze({ loose: true });
4881
+ var emptyOpts = Object.freeze({});
4882
+ var parseOptions = (options) => {
4883
+ if (!options) {
4884
+ return emptyOpts;
4729
4885
  }
4730
- });
4731
- });
4732
- app.get("/api/action-logs", (c) => {
4733
- const moduleId = c.req.query("moduleId");
4734
- const limitStr = c.req.query("limit");
4735
- const limit = limitStr ? parseInt(limitStr, 10) : void 0;
4736
- return c.json(db.listActionLogs({ moduleId, limit }));
4737
- });
4738
- app.get("/api/modules/:module/settings", (c) => {
4739
- const moduleId = c.req.param("module");
4740
- return c.json(db.getModuleSettings(moduleId));
4741
- });
4742
- app.put("/api/modules/:module/settings", async (c) => {
4743
- const moduleId = c.req.param("module");
4744
- const body2 = await c.req.json();
4745
- for (const [key, value] of Object.entries(body2)) {
4746
- db.setModuleSetting(moduleId, key, String(value));
4747
- }
4748
- return c.json({ ok: true });
4749
- });
4750
- app.get("/api/registry/search", async (c) => {
4751
- const q = c.req.query("q") ?? "forge-dev";
4752
- try {
4753
- const npmRes = await globalThis.fetch(`https://registry.npmjs.org/-/v1/search?text=${encodeURIComponent(q)}+keywords:forge-module&size=20`);
4754
- const data = await npmRes.json();
4755
- const results = (data.objects ?? []).map((o) => ({
4756
- name: o.package.name,
4757
- version: o.package.version,
4758
- description: o.package.description
4759
- }));
4760
- return c.json({ results });
4761
- } catch {
4762
- return c.json({ results: [] });
4763
- }
4764
- });
4765
- app.get("/api/filesystem/browse", (c) => {
4766
- const home = process.env.HOME ?? "/tmp";
4767
- const dir = resolve4(c.req.query("path") ?? process.cwd());
4768
- if (!dir.startsWith(home)) {
4769
- return c.json({ error: "Access denied: path must be within home directory" }, 403);
4770
- }
4771
- if (!existsSync13(dir)) {
4772
- return c.json({ error: "Directory not found" }, 404);
4773
- }
4774
- try {
4775
- const entries = readdirSync7(dir, { withFileTypes: true });
4776
- const dirs = entries.filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => ({
4777
- name: e.name,
4778
- path: join14(dir, e.name),
4779
- hasPackageJson: existsSync13(join14(dir, e.name, "package.json")),
4780
- hasGit: existsSync13(join14(dir, e.name, ".git"))
4781
- })).sort((a, b) => a.name.localeCompare(b.name));
4886
+ if (typeof options !== "object") {
4887
+ return looseOption;
4888
+ }
4889
+ return options;
4890
+ };
4891
+ module.exports = parseOptions;
4892
+ }
4893
+ });
4894
+
4895
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/identifiers.js
4896
+ var require_identifiers = __commonJS({
4897
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/identifiers.js"(exports, module) {
4898
+ "use strict";
4899
+ var numeric = /^[0-9]+$/;
4900
+ var compareIdentifiers = (a, b) => {
4901
+ if (typeof a === "number" && typeof b === "number") {
4902
+ return a === b ? 0 : a < b ? -1 : 1;
4903
+ }
4904
+ const anum = numeric.test(a);
4905
+ const bnum = numeric.test(b);
4906
+ if (anum && bnum) {
4907
+ a = +a;
4908
+ b = +b;
4909
+ }
4910
+ return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
4911
+ };
4912
+ var rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);
4913
+ module.exports = {
4914
+ compareIdentifiers,
4915
+ rcompareIdentifiers
4916
+ };
4917
+ }
4918
+ });
4919
+
4920
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/semver.js
4921
+ var require_semver = __commonJS({
4922
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/semver.js"(exports, module) {
4923
+ "use strict";
4924
+ var debug = require_debug();
4925
+ var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants();
4926
+ var { safeRe: re, t } = require_re();
4927
+ var parseOptions = require_parse_options();
4928
+ var { compareIdentifiers } = require_identifiers();
4929
+ var isPrereleaseIdentifier = (prerelease, identifier) => {
4930
+ const identifiers = identifier.split(".");
4931
+ if (identifiers.length > prerelease.length) {
4932
+ return false;
4933
+ }
4934
+ for (let i = 0; i < identifiers.length; i++) {
4935
+ if (compareIdentifiers(prerelease[i], identifiers[i]) !== 0) {
4936
+ return false;
4937
+ }
4938
+ }
4939
+ return true;
4940
+ };
4941
+ var SemVer = class _SemVer {
4942
+ constructor(version, options) {
4943
+ options = parseOptions(options);
4944
+ if (version instanceof _SemVer) {
4945
+ if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) {
4946
+ return version;
4947
+ } else {
4948
+ version = version.version;
4949
+ }
4950
+ } else if (typeof version !== "string") {
4951
+ throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`);
4952
+ }
4953
+ if (version.length > MAX_LENGTH) {
4954
+ throw new TypeError(
4955
+ `version is longer than ${MAX_LENGTH} characters`
4956
+ );
4957
+ }
4958
+ debug("SemVer", version, options);
4959
+ this.options = options;
4960
+ this.loose = !!options.loose;
4961
+ this.includePrerelease = !!options.includePrerelease;
4962
+ const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
4963
+ if (!m) {
4964
+ throw new TypeError(`Invalid Version: ${version}`);
4965
+ }
4966
+ this.raw = version;
4967
+ this.major = +m[1];
4968
+ this.minor = +m[2];
4969
+ this.patch = +m[3];
4970
+ if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
4971
+ throw new TypeError("Invalid major version");
4972
+ }
4973
+ if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
4974
+ throw new TypeError("Invalid minor version");
4975
+ }
4976
+ if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
4977
+ throw new TypeError("Invalid patch version");
4978
+ }
4979
+ if (!m[4]) {
4980
+ this.prerelease = [];
4981
+ } else {
4982
+ this.prerelease = m[4].split(".").map((id) => {
4983
+ if (/^[0-9]+$/.test(id)) {
4984
+ const num2 = +id;
4985
+ if (num2 >= 0 && num2 < MAX_SAFE_INTEGER) {
4986
+ return num2;
4987
+ }
4988
+ }
4989
+ return id;
4990
+ });
4991
+ }
4992
+ this.build = m[5] ? m[5].split(".") : [];
4993
+ this.format();
4994
+ }
4995
+ format() {
4996
+ this.version = `${this.major}.${this.minor}.${this.patch}`;
4997
+ if (this.prerelease.length) {
4998
+ this.version += `-${this.prerelease.join(".")}`;
4999
+ }
5000
+ return this.version;
5001
+ }
5002
+ toString() {
5003
+ return this.version;
5004
+ }
5005
+ compare(other) {
5006
+ debug("SemVer.compare", this.version, this.options, other);
5007
+ if (!(other instanceof _SemVer)) {
5008
+ if (typeof other === "string" && other === this.version) {
5009
+ return 0;
5010
+ }
5011
+ other = new _SemVer(other, this.options);
5012
+ }
5013
+ if (other.version === this.version) {
5014
+ return 0;
5015
+ }
5016
+ return this.compareMain(other) || this.comparePre(other);
5017
+ }
5018
+ compareMain(other) {
5019
+ if (!(other instanceof _SemVer)) {
5020
+ other = new _SemVer(other, this.options);
5021
+ }
5022
+ if (this.major < other.major) {
5023
+ return -1;
5024
+ }
5025
+ if (this.major > other.major) {
5026
+ return 1;
5027
+ }
5028
+ if (this.minor < other.minor) {
5029
+ return -1;
5030
+ }
5031
+ if (this.minor > other.minor) {
5032
+ return 1;
5033
+ }
5034
+ if (this.patch < other.patch) {
5035
+ return -1;
5036
+ }
5037
+ if (this.patch > other.patch) {
5038
+ return 1;
5039
+ }
5040
+ return 0;
5041
+ }
5042
+ comparePre(other) {
5043
+ if (!(other instanceof _SemVer)) {
5044
+ other = new _SemVer(other, this.options);
5045
+ }
5046
+ if (this.prerelease.length && !other.prerelease.length) {
5047
+ return -1;
5048
+ } else if (!this.prerelease.length && other.prerelease.length) {
5049
+ return 1;
5050
+ } else if (!this.prerelease.length && !other.prerelease.length) {
5051
+ return 0;
5052
+ }
5053
+ let i = 0;
5054
+ do {
5055
+ const a = this.prerelease[i];
5056
+ const b = other.prerelease[i];
5057
+ debug("prerelease compare", i, a, b);
5058
+ if (a === void 0 && b === void 0) {
5059
+ return 0;
5060
+ } else if (b === void 0) {
5061
+ return 1;
5062
+ } else if (a === void 0) {
5063
+ return -1;
5064
+ } else if (a === b) {
5065
+ continue;
5066
+ } else {
5067
+ return compareIdentifiers(a, b);
5068
+ }
5069
+ } while (++i);
5070
+ }
5071
+ compareBuild(other) {
5072
+ if (!(other instanceof _SemVer)) {
5073
+ other = new _SemVer(other, this.options);
5074
+ }
5075
+ let i = 0;
5076
+ do {
5077
+ const a = this.build[i];
5078
+ const b = other.build[i];
5079
+ debug("build compare", i, a, b);
5080
+ if (a === void 0 && b === void 0) {
5081
+ return 0;
5082
+ } else if (b === void 0) {
5083
+ return 1;
5084
+ } else if (a === void 0) {
5085
+ return -1;
5086
+ } else if (a === b) {
5087
+ continue;
5088
+ } else {
5089
+ return compareIdentifiers(a, b);
5090
+ }
5091
+ } while (++i);
5092
+ }
5093
+ // preminor will bump the version up to the next minor release, and immediately
5094
+ // down to pre-release. premajor and prepatch work the same way.
5095
+ inc(release, identifier, identifierBase) {
5096
+ if (release.startsWith("pre")) {
5097
+ if (!identifier && identifierBase === false) {
5098
+ throw new Error("invalid increment argument: identifier is empty");
5099
+ }
5100
+ if (identifier) {
5101
+ const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]);
5102
+ if (!match || match[1] !== identifier) {
5103
+ throw new Error(`invalid identifier: ${identifier}`);
5104
+ }
5105
+ }
5106
+ }
5107
+ switch (release) {
5108
+ case "premajor":
5109
+ this.prerelease.length = 0;
5110
+ this.patch = 0;
5111
+ this.minor = 0;
5112
+ this.major++;
5113
+ this.inc("pre", identifier, identifierBase);
5114
+ break;
5115
+ case "preminor":
5116
+ this.prerelease.length = 0;
5117
+ this.patch = 0;
5118
+ this.minor++;
5119
+ this.inc("pre", identifier, identifierBase);
5120
+ break;
5121
+ case "prepatch":
5122
+ this.prerelease.length = 0;
5123
+ this.inc("patch", identifier, identifierBase);
5124
+ this.inc("pre", identifier, identifierBase);
5125
+ break;
5126
+ // If the input is a non-prerelease version, this acts the same as
5127
+ // prepatch.
5128
+ case "prerelease":
5129
+ if (this.prerelease.length === 0) {
5130
+ this.inc("patch", identifier, identifierBase);
5131
+ }
5132
+ this.inc("pre", identifier, identifierBase);
5133
+ break;
5134
+ case "release":
5135
+ if (this.prerelease.length === 0) {
5136
+ throw new Error(`version ${this.raw} is not a prerelease`);
5137
+ }
5138
+ this.prerelease.length = 0;
5139
+ break;
5140
+ case "major":
5141
+ if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
5142
+ this.major++;
5143
+ }
5144
+ this.minor = 0;
5145
+ this.patch = 0;
5146
+ this.prerelease = [];
5147
+ break;
5148
+ case "minor":
5149
+ if (this.patch !== 0 || this.prerelease.length === 0) {
5150
+ this.minor++;
5151
+ }
5152
+ this.patch = 0;
5153
+ this.prerelease = [];
5154
+ break;
5155
+ case "patch":
5156
+ if (this.prerelease.length === 0) {
5157
+ this.patch++;
5158
+ }
5159
+ this.prerelease = [];
5160
+ break;
5161
+ // This probably shouldn't be used publicly.
5162
+ // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
5163
+ case "pre": {
5164
+ const base = Number(identifierBase) ? 1 : 0;
5165
+ if (this.prerelease.length === 0) {
5166
+ this.prerelease = [base];
5167
+ } else {
5168
+ let i = this.prerelease.length;
5169
+ while (--i >= 0) {
5170
+ if (typeof this.prerelease[i] === "number") {
5171
+ this.prerelease[i]++;
5172
+ i = -2;
5173
+ }
5174
+ }
5175
+ if (i === -1) {
5176
+ if (identifier === this.prerelease.join(".") && identifierBase === false) {
5177
+ throw new Error("invalid increment argument: identifier already exists");
5178
+ }
5179
+ this.prerelease.push(base);
5180
+ }
5181
+ }
5182
+ if (identifier) {
5183
+ let prerelease = [identifier, base];
5184
+ if (identifierBase === false) {
5185
+ prerelease = [identifier];
5186
+ }
5187
+ if (isPrereleaseIdentifier(this.prerelease, identifier)) {
5188
+ const prereleaseBase = this.prerelease[identifier.split(".").length];
5189
+ if (isNaN(prereleaseBase)) {
5190
+ this.prerelease = prerelease;
5191
+ }
5192
+ } else {
5193
+ this.prerelease = prerelease;
5194
+ }
5195
+ }
5196
+ break;
5197
+ }
5198
+ default:
5199
+ throw new Error(`invalid increment argument: ${release}`);
5200
+ }
5201
+ this.raw = this.format();
5202
+ if (this.build.length) {
5203
+ this.raw += `+${this.build.join(".")}`;
5204
+ }
5205
+ return this;
5206
+ }
5207
+ };
5208
+ module.exports = SemVer;
5209
+ }
5210
+ });
5211
+
5212
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/parse.js
5213
+ var require_parse = __commonJS({
5214
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/parse.js"(exports, module) {
5215
+ "use strict";
5216
+ var SemVer = require_semver();
5217
+ var parse = (version, options, throwErrors = false) => {
5218
+ if (version instanceof SemVer) {
5219
+ return version;
5220
+ }
5221
+ try {
5222
+ return new SemVer(version, options);
5223
+ } catch (er) {
5224
+ if (!throwErrors) {
5225
+ return null;
5226
+ }
5227
+ throw er;
5228
+ }
5229
+ };
5230
+ module.exports = parse;
5231
+ }
5232
+ });
5233
+
5234
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/valid.js
5235
+ var require_valid = __commonJS({
5236
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/valid.js"(exports, module) {
5237
+ "use strict";
5238
+ var parse = require_parse();
5239
+ var valid = (version, options) => {
5240
+ const v = parse(version, options);
5241
+ return v ? v.version : null;
5242
+ };
5243
+ module.exports = valid;
5244
+ }
5245
+ });
5246
+
5247
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/clean.js
5248
+ var require_clean = __commonJS({
5249
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/clean.js"(exports, module) {
5250
+ "use strict";
5251
+ var parse = require_parse();
5252
+ var clean = (version, options) => {
5253
+ const s = parse(version.trim().replace(/^[=v]+/, ""), options);
5254
+ return s ? s.version : null;
5255
+ };
5256
+ module.exports = clean;
5257
+ }
5258
+ });
5259
+
5260
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/inc.js
5261
+ var require_inc = __commonJS({
5262
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/inc.js"(exports, module) {
5263
+ "use strict";
5264
+ var SemVer = require_semver();
5265
+ var inc = (version, release, options, identifier, identifierBase) => {
5266
+ if (typeof options === "string") {
5267
+ identifierBase = identifier;
5268
+ identifier = options;
5269
+ options = void 0;
5270
+ }
5271
+ try {
5272
+ return new SemVer(
5273
+ version instanceof SemVer ? version.version : version,
5274
+ options
5275
+ ).inc(release, identifier, identifierBase).version;
5276
+ } catch (er) {
5277
+ return null;
5278
+ }
5279
+ };
5280
+ module.exports = inc;
5281
+ }
5282
+ });
5283
+
5284
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/diff.js
5285
+ var require_diff = __commonJS({
5286
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/diff.js"(exports, module) {
5287
+ "use strict";
5288
+ var parse = require_parse();
5289
+ var diff = (version1, version2) => {
5290
+ const v1 = parse(version1, null, true);
5291
+ const v2 = parse(version2, null, true);
5292
+ const comparison = v1.compare(v2);
5293
+ if (comparison === 0) {
5294
+ return null;
5295
+ }
5296
+ const v1Higher = comparison > 0;
5297
+ const highVersion = v1Higher ? v1 : v2;
5298
+ const lowVersion = v1Higher ? v2 : v1;
5299
+ const highHasPre = !!highVersion.prerelease.length;
5300
+ const lowHasPre = !!lowVersion.prerelease.length;
5301
+ if (lowHasPre && !highHasPre) {
5302
+ if (!lowVersion.patch && !lowVersion.minor) {
5303
+ return "major";
5304
+ }
5305
+ if (lowVersion.compareMain(highVersion) === 0) {
5306
+ if (lowVersion.minor && !lowVersion.patch) {
5307
+ return "minor";
5308
+ }
5309
+ return "patch";
5310
+ }
5311
+ }
5312
+ const prefix = highHasPre ? "pre" : "";
5313
+ if (v1.major !== v2.major) {
5314
+ return prefix + "major";
5315
+ }
5316
+ if (v1.minor !== v2.minor) {
5317
+ return prefix + "minor";
5318
+ }
5319
+ if (v1.patch !== v2.patch) {
5320
+ return prefix + "patch";
5321
+ }
5322
+ return "prerelease";
5323
+ };
5324
+ module.exports = diff;
5325
+ }
5326
+ });
5327
+
5328
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/major.js
5329
+ var require_major = __commonJS({
5330
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/major.js"(exports, module) {
5331
+ "use strict";
5332
+ var SemVer = require_semver();
5333
+ var major = (a, loose) => new SemVer(a, loose).major;
5334
+ module.exports = major;
5335
+ }
5336
+ });
5337
+
5338
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/minor.js
5339
+ var require_minor = __commonJS({
5340
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/minor.js"(exports, module) {
5341
+ "use strict";
5342
+ var SemVer = require_semver();
5343
+ var minor = (a, loose) => new SemVer(a, loose).minor;
5344
+ module.exports = minor;
5345
+ }
5346
+ });
5347
+
5348
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/patch.js
5349
+ var require_patch = __commonJS({
5350
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/patch.js"(exports, module) {
5351
+ "use strict";
5352
+ var SemVer = require_semver();
5353
+ var patch = (a, loose) => new SemVer(a, loose).patch;
5354
+ module.exports = patch;
5355
+ }
5356
+ });
5357
+
5358
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/prerelease.js
5359
+ var require_prerelease = __commonJS({
5360
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/prerelease.js"(exports, module) {
5361
+ "use strict";
5362
+ var parse = require_parse();
5363
+ var prerelease = (version, options) => {
5364
+ const parsed = parse(version, options);
5365
+ return parsed && parsed.prerelease.length ? parsed.prerelease : null;
5366
+ };
5367
+ module.exports = prerelease;
5368
+ }
5369
+ });
5370
+
5371
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare.js
5372
+ var require_compare = __commonJS({
5373
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare.js"(exports, module) {
5374
+ "use strict";
5375
+ var SemVer = require_semver();
5376
+ var compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose));
5377
+ module.exports = compare;
5378
+ }
5379
+ });
5380
+
5381
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/rcompare.js
5382
+ var require_rcompare = __commonJS({
5383
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/rcompare.js"(exports, module) {
5384
+ "use strict";
5385
+ var compare = require_compare();
5386
+ var rcompare = (a, b, loose) => compare(b, a, loose);
5387
+ module.exports = rcompare;
5388
+ }
5389
+ });
5390
+
5391
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare-loose.js
5392
+ var require_compare_loose = __commonJS({
5393
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare-loose.js"(exports, module) {
5394
+ "use strict";
5395
+ var compare = require_compare();
5396
+ var compareLoose = (a, b) => compare(a, b, true);
5397
+ module.exports = compareLoose;
5398
+ }
5399
+ });
5400
+
5401
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare-build.js
5402
+ var require_compare_build = __commonJS({
5403
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare-build.js"(exports, module) {
5404
+ "use strict";
5405
+ var SemVer = require_semver();
5406
+ var compareBuild = (a, b, loose) => {
5407
+ const versionA = new SemVer(a, loose);
5408
+ const versionB = new SemVer(b, loose);
5409
+ return versionA.compare(versionB) || versionA.compareBuild(versionB);
5410
+ };
5411
+ module.exports = compareBuild;
5412
+ }
5413
+ });
5414
+
5415
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/sort.js
5416
+ var require_sort = __commonJS({
5417
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/sort.js"(exports, module) {
5418
+ "use strict";
5419
+ var compareBuild = require_compare_build();
5420
+ var sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose));
5421
+ module.exports = sort;
5422
+ }
5423
+ });
5424
+
5425
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/rsort.js
5426
+ var require_rsort = __commonJS({
5427
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/rsort.js"(exports, module) {
5428
+ "use strict";
5429
+ var compareBuild = require_compare_build();
5430
+ var rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose));
5431
+ module.exports = rsort;
5432
+ }
5433
+ });
5434
+
5435
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gt.js
5436
+ var require_gt = __commonJS({
5437
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gt.js"(exports, module) {
5438
+ "use strict";
5439
+ var compare = require_compare();
5440
+ var gt = (a, b, loose) => compare(a, b, loose) > 0;
5441
+ module.exports = gt;
5442
+ }
5443
+ });
5444
+
5445
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/lt.js
5446
+ var require_lt = __commonJS({
5447
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/lt.js"(exports, module) {
5448
+ "use strict";
5449
+ var compare = require_compare();
5450
+ var lt = (a, b, loose) => compare(a, b, loose) < 0;
5451
+ module.exports = lt;
5452
+ }
5453
+ });
5454
+
5455
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/eq.js
5456
+ var require_eq = __commonJS({
5457
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/eq.js"(exports, module) {
5458
+ "use strict";
5459
+ var compare = require_compare();
5460
+ var eq = (a, b, loose) => compare(a, b, loose) === 0;
5461
+ module.exports = eq;
5462
+ }
5463
+ });
5464
+
5465
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/neq.js
5466
+ var require_neq = __commonJS({
5467
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/neq.js"(exports, module) {
5468
+ "use strict";
5469
+ var compare = require_compare();
5470
+ var neq = (a, b, loose) => compare(a, b, loose) !== 0;
5471
+ module.exports = neq;
5472
+ }
5473
+ });
5474
+
5475
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gte.js
5476
+ var require_gte = __commonJS({
5477
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gte.js"(exports, module) {
5478
+ "use strict";
5479
+ var compare = require_compare();
5480
+ var gte = (a, b, loose) => compare(a, b, loose) >= 0;
5481
+ module.exports = gte;
5482
+ }
5483
+ });
5484
+
5485
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/lte.js
5486
+ var require_lte = __commonJS({
5487
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/lte.js"(exports, module) {
5488
+ "use strict";
5489
+ var compare = require_compare();
5490
+ var lte = (a, b, loose) => compare(a, b, loose) <= 0;
5491
+ module.exports = lte;
5492
+ }
5493
+ });
5494
+
5495
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/cmp.js
5496
+ var require_cmp = __commonJS({
5497
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/cmp.js"(exports, module) {
5498
+ "use strict";
5499
+ var eq = require_eq();
5500
+ var neq = require_neq();
5501
+ var gt = require_gt();
5502
+ var gte = require_gte();
5503
+ var lt = require_lt();
5504
+ var lte = require_lte();
5505
+ var cmp = (a, op, b, loose) => {
5506
+ switch (op) {
5507
+ case "===":
5508
+ if (typeof a === "object") {
5509
+ a = a.version;
5510
+ }
5511
+ if (typeof b === "object") {
5512
+ b = b.version;
5513
+ }
5514
+ return a === b;
5515
+ case "!==":
5516
+ if (typeof a === "object") {
5517
+ a = a.version;
5518
+ }
5519
+ if (typeof b === "object") {
5520
+ b = b.version;
5521
+ }
5522
+ return a !== b;
5523
+ case "":
5524
+ case "=":
5525
+ case "==":
5526
+ return eq(a, b, loose);
5527
+ case "!=":
5528
+ return neq(a, b, loose);
5529
+ case ">":
5530
+ return gt(a, b, loose);
5531
+ case ">=":
5532
+ return gte(a, b, loose);
5533
+ case "<":
5534
+ return lt(a, b, loose);
5535
+ case "<=":
5536
+ return lte(a, b, loose);
5537
+ default:
5538
+ throw new TypeError(`Invalid operator: ${op}`);
5539
+ }
5540
+ };
5541
+ module.exports = cmp;
5542
+ }
5543
+ });
5544
+
5545
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/coerce.js
5546
+ var require_coerce = __commonJS({
5547
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/coerce.js"(exports, module) {
5548
+ "use strict";
5549
+ var SemVer = require_semver();
5550
+ var parse = require_parse();
5551
+ var { safeRe: re, t } = require_re();
5552
+ var coerce = (version, options) => {
5553
+ if (version instanceof SemVer) {
5554
+ return version;
5555
+ }
5556
+ if (typeof version === "number") {
5557
+ version = String(version);
5558
+ }
5559
+ if (typeof version !== "string") {
5560
+ return null;
5561
+ }
5562
+ options = options || {};
5563
+ let match = null;
5564
+ if (!options.rtl) {
5565
+ match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]);
5566
+ } else {
5567
+ const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL];
5568
+ let next;
5569
+ while ((next = coerceRtlRegex.exec(version)) && (!match || match.index + match[0].length !== version.length)) {
5570
+ if (!match || next.index + next[0].length !== match.index + match[0].length) {
5571
+ match = next;
5572
+ }
5573
+ coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length;
5574
+ }
5575
+ coerceRtlRegex.lastIndex = -1;
5576
+ }
5577
+ if (match === null) {
5578
+ return null;
5579
+ }
5580
+ const major = match[2];
5581
+ const minor = match[3] || "0";
5582
+ const patch = match[4] || "0";
5583
+ const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : "";
5584
+ const build = options.includePrerelease && match[6] ? `+${match[6]}` : "";
5585
+ return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options);
5586
+ };
5587
+ module.exports = coerce;
5588
+ }
5589
+ });
5590
+
5591
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/truncate.js
5592
+ var require_truncate = __commonJS({
5593
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/truncate.js"(exports, module) {
5594
+ "use strict";
5595
+ var parse = require_parse();
5596
+ var constants3 = require_constants();
5597
+ var SemVer = require_semver();
5598
+ var truncate = (version, truncation, options) => {
5599
+ if (!constants3.RELEASE_TYPES.includes(truncation)) {
5600
+ return null;
5601
+ }
5602
+ const clonedVersion = cloneInputVersion(version, options);
5603
+ return clonedVersion && doTruncation(clonedVersion, truncation);
5604
+ };
5605
+ var cloneInputVersion = (version, options) => {
5606
+ const versionStringToParse = version instanceof SemVer ? version.version : version;
5607
+ return parse(versionStringToParse, options);
5608
+ };
5609
+ var doTruncation = (version, truncation) => {
5610
+ if (isPrerelease(truncation)) {
5611
+ return version.version;
5612
+ }
5613
+ version.prerelease = [];
5614
+ switch (truncation) {
5615
+ case "major":
5616
+ version.minor = 0;
5617
+ version.patch = 0;
5618
+ break;
5619
+ case "minor":
5620
+ version.patch = 0;
5621
+ break;
5622
+ }
5623
+ return version.format();
5624
+ };
5625
+ var isPrerelease = (type) => {
5626
+ return type.startsWith("pre");
5627
+ };
5628
+ module.exports = truncate;
5629
+ }
5630
+ });
5631
+
5632
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/lrucache.js
5633
+ var require_lrucache = __commonJS({
5634
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/lrucache.js"(exports, module) {
5635
+ "use strict";
5636
+ var LRUCache = class {
5637
+ constructor() {
5638
+ this.max = 1e3;
5639
+ this.map = /* @__PURE__ */ new Map();
5640
+ }
5641
+ get(key) {
5642
+ const value = this.map.get(key);
5643
+ if (value === void 0) {
5644
+ return void 0;
5645
+ } else {
5646
+ this.map.delete(key);
5647
+ this.map.set(key, value);
5648
+ return value;
5649
+ }
5650
+ }
5651
+ delete(key) {
5652
+ return this.map.delete(key);
5653
+ }
5654
+ set(key, value) {
5655
+ const deleted = this.delete(key);
5656
+ if (!deleted && value !== void 0) {
5657
+ if (this.map.size >= this.max) {
5658
+ const firstKey = this.map.keys().next().value;
5659
+ this.delete(firstKey);
5660
+ }
5661
+ this.map.set(key, value);
5662
+ }
5663
+ return this;
5664
+ }
5665
+ };
5666
+ module.exports = LRUCache;
5667
+ }
5668
+ });
5669
+
5670
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/range.js
5671
+ var require_range = __commonJS({
5672
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/range.js"(exports, module) {
5673
+ "use strict";
5674
+ var SPACE_CHARACTERS = /\s+/g;
5675
+ var Range = class _Range {
5676
+ constructor(range, options) {
5677
+ options = parseOptions(options);
5678
+ if (range instanceof _Range) {
5679
+ if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
5680
+ return range;
5681
+ } else {
5682
+ return new _Range(range.raw, options);
5683
+ }
5684
+ }
5685
+ if (range instanceof Comparator) {
5686
+ this.raw = range.value;
5687
+ this.set = [[range]];
5688
+ this.formatted = void 0;
5689
+ return this;
5690
+ }
5691
+ this.options = options;
5692
+ this.loose = !!options.loose;
5693
+ this.includePrerelease = !!options.includePrerelease;
5694
+ this.raw = range.trim().replace(SPACE_CHARACTERS, " ");
5695
+ this.set = this.raw.split("||").map((r) => this.parseRange(r.trim())).filter((c) => c.length);
5696
+ if (!this.set.length) {
5697
+ throw new TypeError(`Invalid SemVer Range: ${this.raw}`);
5698
+ }
5699
+ if (this.set.length > 1) {
5700
+ const first = this.set[0];
5701
+ this.set = this.set.filter((c) => !isNullSet(c[0]));
5702
+ if (this.set.length === 0) {
5703
+ this.set = [first];
5704
+ } else if (this.set.length > 1) {
5705
+ for (const c of this.set) {
5706
+ if (c.length === 1 && isAny(c[0])) {
5707
+ this.set = [c];
5708
+ break;
5709
+ }
5710
+ }
5711
+ }
5712
+ }
5713
+ this.formatted = void 0;
5714
+ }
5715
+ get range() {
5716
+ if (this.formatted === void 0) {
5717
+ this.formatted = "";
5718
+ for (let i = 0; i < this.set.length; i++) {
5719
+ if (i > 0) {
5720
+ this.formatted += "||";
5721
+ }
5722
+ const comps = this.set[i];
5723
+ for (let k = 0; k < comps.length; k++) {
5724
+ if (k > 0) {
5725
+ this.formatted += " ";
5726
+ }
5727
+ this.formatted += comps[k].toString().trim();
5728
+ }
5729
+ }
5730
+ }
5731
+ return this.formatted;
5732
+ }
5733
+ format() {
5734
+ return this.range;
5735
+ }
5736
+ toString() {
5737
+ return this.range;
5738
+ }
5739
+ parseRange(range) {
5740
+ range = range.replace(BUILDSTRIPRE, "");
5741
+ const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);
5742
+ const memoKey = memoOpts + ":" + range;
5743
+ const cached = cache.get(memoKey);
5744
+ if (cached) {
5745
+ return cached;
5746
+ }
5747
+ const loose = this.options.loose;
5748
+ const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
5749
+ range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
5750
+ debug("hyphen replace", range);
5751
+ range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
5752
+ debug("comparator trim", range);
5753
+ range = range.replace(re[t.TILDETRIM], tildeTrimReplace);
5754
+ debug("tilde trim", range);
5755
+ range = range.replace(re[t.CARETTRIM], caretTrimReplace);
5756
+ debug("caret trim", range);
5757
+ let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options));
5758
+ if (loose) {
5759
+ rangeList = rangeList.filter((comp) => {
5760
+ debug("loose invalid filter", comp, this.options);
5761
+ return !!comp.match(re[t.COMPARATORLOOSE]);
5762
+ });
5763
+ }
5764
+ debug("range list", rangeList);
5765
+ const rangeMap = /* @__PURE__ */ new Map();
5766
+ const comparators = rangeList.map((comp) => new Comparator(comp, this.options));
5767
+ for (const comp of comparators) {
5768
+ if (isNullSet(comp)) {
5769
+ return [comp];
5770
+ }
5771
+ rangeMap.set(comp.value, comp);
5772
+ }
5773
+ if (rangeMap.size > 1 && rangeMap.has("")) {
5774
+ rangeMap.delete("");
5775
+ }
5776
+ const result2 = [...rangeMap.values()];
5777
+ cache.set(memoKey, result2);
5778
+ return result2;
5779
+ }
5780
+ intersects(range, options) {
5781
+ if (!(range instanceof _Range)) {
5782
+ throw new TypeError("a Range is required");
5783
+ }
5784
+ return this.set.some((thisComparators) => {
5785
+ return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => {
5786
+ return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => {
5787
+ return rangeComparators.every((rangeComparator) => {
5788
+ return thisComparator.intersects(rangeComparator, options);
5789
+ });
5790
+ });
5791
+ });
5792
+ });
5793
+ }
5794
+ // if ANY of the sets match ALL of its comparators, then pass
5795
+ test(version) {
5796
+ if (!version) {
5797
+ return false;
5798
+ }
5799
+ if (typeof version === "string") {
5800
+ try {
5801
+ version = new SemVer(version, this.options);
5802
+ } catch (er) {
5803
+ return false;
5804
+ }
5805
+ }
5806
+ for (let i = 0; i < this.set.length; i++) {
5807
+ if (testSet(this.set[i], version, this.options)) {
5808
+ return true;
5809
+ }
5810
+ }
5811
+ return false;
5812
+ }
5813
+ };
5814
+ module.exports = Range;
5815
+ var LRU = require_lrucache();
5816
+ var cache = new LRU();
5817
+ var parseOptions = require_parse_options();
5818
+ var Comparator = require_comparator();
5819
+ var debug = require_debug();
5820
+ var SemVer = require_semver();
5821
+ var {
5822
+ safeRe: re,
5823
+ src,
5824
+ t,
5825
+ comparatorTrimReplace,
5826
+ tildeTrimReplace,
5827
+ caretTrimReplace
5828
+ } = require_re();
5829
+ var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants();
5830
+ var BUILDSTRIPRE = new RegExp(src[t.BUILD], "g");
5831
+ var isNullSet = (c) => c.value === "<0.0.0-0";
5832
+ var isAny = (c) => c.value === "";
5833
+ var isSatisfiable = (comparators, options) => {
5834
+ let result2 = true;
5835
+ const remainingComparators = comparators.slice();
5836
+ let testComparator = remainingComparators.pop();
5837
+ while (result2 && remainingComparators.length) {
5838
+ result2 = remainingComparators.every((otherComparator) => {
5839
+ return testComparator.intersects(otherComparator, options);
5840
+ });
5841
+ testComparator = remainingComparators.pop();
5842
+ }
5843
+ return result2;
5844
+ };
5845
+ var parseComparator = (comp, options) => {
5846
+ comp = comp.replace(re[t.BUILD], "");
5847
+ debug("comp", comp, options);
5848
+ comp = replaceCarets(comp, options);
5849
+ debug("caret", comp);
5850
+ comp = replaceTildes(comp, options);
5851
+ debug("tildes", comp);
5852
+ comp = replaceXRanges(comp, options);
5853
+ debug("xrange", comp);
5854
+ comp = replaceStars(comp, options);
5855
+ debug("stars", comp);
5856
+ return comp;
5857
+ };
5858
+ var isX = (id) => !id || id.toLowerCase() === "x" || id === "*";
5859
+ var invalidXRangeOrder = (M, m, p) => isX(M) && !isX(m) || isX(m) && p && !isX(p);
5860
+ var replaceTildes = (comp, options) => {
5861
+ return comp.trim().split(/\s+/).map((c) => replaceTilde(c, options)).join(" ");
5862
+ };
5863
+ var replaceTilde = (comp, options) => {
5864
+ const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
5865
+ const z = options.includePrerelease ? "-0" : "";
5866
+ return comp.replace(r, (_, M, m, p, pr) => {
5867
+ debug("tilde", comp, _, M, m, p, pr);
5868
+ let ret;
5869
+ if (isX(M)) {
5870
+ ret = "";
5871
+ } else if (isX(m)) {
5872
+ ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
5873
+ } else if (isX(p)) {
5874
+ ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
5875
+ } else if (pr) {
5876
+ debug("replaceTilde pr", pr);
5877
+ ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
5878
+ } else {
5879
+ ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;
5880
+ }
5881
+ debug("tilde return", ret);
5882
+ return ret;
5883
+ });
5884
+ };
5885
+ var replaceCarets = (comp, options) => {
5886
+ return comp.trim().split(/\s+/).map((c) => replaceCaret(c, options)).join(" ");
5887
+ };
5888
+ var replaceCaret = (comp, options) => {
5889
+ debug("caret", comp, options);
5890
+ const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
5891
+ const z = options.includePrerelease ? "-0" : "";
5892
+ return comp.replace(r, (_, M, m, p, pr) => {
5893
+ debug("caret", comp, _, M, m, p, pr);
5894
+ let ret;
5895
+ if (isX(M)) {
5896
+ ret = "";
5897
+ } else if (isX(m)) {
5898
+ ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
5899
+ } else if (isX(p)) {
5900
+ if (M === "0") {
5901
+ ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
5902
+ } else {
5903
+ ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
5904
+ }
5905
+ } else if (pr) {
5906
+ debug("replaceCaret pr", pr);
5907
+ if (M === "0") {
5908
+ if (m === "0") {
5909
+ ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`;
5910
+ } else {
5911
+ ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
5912
+ }
5913
+ } else {
5914
+ ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`;
5915
+ }
5916
+ } else {
5917
+ debug("no pr");
5918
+ if (M === "0") {
5919
+ if (m === "0") {
5920
+ ret = `>=${M}.${m}.${p} <${M}.${m}.${+p + 1}-0`;
5921
+ } else {
5922
+ ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;
5923
+ }
5924
+ } else {
5925
+ ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`;
5926
+ }
5927
+ }
5928
+ debug("caret return", ret);
5929
+ return ret;
5930
+ });
5931
+ };
5932
+ var replaceXRanges = (comp, options) => {
5933
+ debug("replaceXRanges", comp, options);
5934
+ return comp.split(/\s+/).map((c) => replaceXRange(c, options)).join(" ");
5935
+ };
5936
+ var replaceXRange = (comp, options) => {
5937
+ comp = comp.trim();
5938
+ const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
5939
+ return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
5940
+ debug("xRange", comp, ret, gtlt, M, m, p, pr);
5941
+ if (invalidXRangeOrder(M, m, p)) {
5942
+ return comp;
5943
+ }
5944
+ const xM = isX(M);
5945
+ const xm = xM || isX(m);
5946
+ const xp = xm || isX(p);
5947
+ const anyX = xp;
5948
+ if (gtlt === "=" && anyX) {
5949
+ gtlt = "";
5950
+ }
5951
+ pr = options.includePrerelease ? "-0" : "";
5952
+ if (xM) {
5953
+ if (gtlt === ">" || gtlt === "<") {
5954
+ ret = "<0.0.0-0";
5955
+ } else {
5956
+ ret = "*";
5957
+ }
5958
+ } else if (gtlt && anyX) {
5959
+ if (xm) {
5960
+ m = 0;
5961
+ }
5962
+ p = 0;
5963
+ if (gtlt === ">") {
5964
+ gtlt = ">=";
5965
+ if (xm) {
5966
+ M = +M + 1;
5967
+ m = 0;
5968
+ p = 0;
5969
+ } else {
5970
+ m = +m + 1;
5971
+ p = 0;
5972
+ }
5973
+ } else if (gtlt === "<=") {
5974
+ gtlt = "<";
5975
+ if (xm) {
5976
+ M = +M + 1;
5977
+ } else {
5978
+ m = +m + 1;
5979
+ }
5980
+ }
5981
+ if (gtlt === "<") {
5982
+ pr = "-0";
5983
+ }
5984
+ ret = `${gtlt + M}.${m}.${p}${pr}`;
5985
+ } else if (xm) {
5986
+ ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
5987
+ } else if (xp) {
5988
+ ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`;
5989
+ }
5990
+ debug("xRange return", ret);
5991
+ return ret;
5992
+ });
5993
+ };
5994
+ var replaceStars = (comp, options) => {
5995
+ debug("replaceStars", comp, options);
5996
+ return comp.trim().replace(re[t.STAR], "");
5997
+ };
5998
+ var replaceGTE0 = (comp, options) => {
5999
+ debug("replaceGTE0", comp, options);
6000
+ return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], "");
6001
+ };
6002
+ var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
6003
+ if (isX(fM)) {
6004
+ from = "";
6005
+ } else if (isX(fm)) {
6006
+ from = `>=${fM}.0.0${incPr ? "-0" : ""}`;
6007
+ } else if (isX(fp)) {
6008
+ from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;
6009
+ } else if (fpr) {
6010
+ from = `>=${from}`;
6011
+ } else {
6012
+ from = `>=${from}${incPr ? "-0" : ""}`;
6013
+ }
6014
+ if (isX(tM)) {
6015
+ to = "";
6016
+ } else if (isX(tm)) {
6017
+ to = `<${+tM + 1}.0.0-0`;
6018
+ } else if (isX(tp)) {
6019
+ to = `<${tM}.${+tm + 1}.0-0`;
6020
+ } else if (tpr) {
6021
+ to = `<=${tM}.${tm}.${tp}-${tpr}`;
6022
+ } else if (incPr) {
6023
+ to = `<${tM}.${tm}.${+tp + 1}-0`;
6024
+ } else {
6025
+ to = `<=${to}`;
6026
+ }
6027
+ return `${from} ${to}`.trim();
6028
+ };
6029
+ var testSet = (set, version, options) => {
6030
+ for (let i = 0; i < set.length; i++) {
6031
+ if (!set[i].test(version)) {
6032
+ return false;
6033
+ }
6034
+ }
6035
+ if (version.prerelease.length && !options.includePrerelease) {
6036
+ for (let i = 0; i < set.length; i++) {
6037
+ debug(set[i].semver);
6038
+ if (set[i].semver === Comparator.ANY) {
6039
+ continue;
6040
+ }
6041
+ if (set[i].semver.prerelease.length > 0) {
6042
+ const allowed = set[i].semver;
6043
+ if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
6044
+ return true;
6045
+ }
6046
+ }
6047
+ }
6048
+ return false;
6049
+ }
6050
+ return true;
6051
+ };
6052
+ }
6053
+ });
6054
+
6055
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/comparator.js
6056
+ var require_comparator = __commonJS({
6057
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/comparator.js"(exports, module) {
6058
+ "use strict";
6059
+ var ANY = Symbol("SemVer ANY");
6060
+ var Comparator = class _Comparator {
6061
+ static get ANY() {
6062
+ return ANY;
6063
+ }
6064
+ constructor(comp, options) {
6065
+ options = parseOptions(options);
6066
+ if (comp instanceof _Comparator) {
6067
+ if (comp.loose === !!options.loose) {
6068
+ return comp;
6069
+ } else {
6070
+ comp = comp.value;
6071
+ }
6072
+ }
6073
+ comp = comp.trim().split(/\s+/).join(" ");
6074
+ debug("comparator", comp, options);
6075
+ this.options = options;
6076
+ this.loose = !!options.loose;
6077
+ this.parse(comp);
6078
+ if (this.semver === ANY) {
6079
+ this.value = "";
6080
+ } else {
6081
+ this.value = this.operator + this.semver.version;
6082
+ }
6083
+ debug("comp", this);
6084
+ }
6085
+ parse(comp) {
6086
+ const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
6087
+ const m = comp.match(r);
6088
+ if (!m) {
6089
+ throw new TypeError(`Invalid comparator: ${comp}`);
6090
+ }
6091
+ this.operator = m[1] !== void 0 ? m[1] : "";
6092
+ if (this.operator === "=") {
6093
+ this.operator = "";
6094
+ }
6095
+ if (!m[2]) {
6096
+ this.semver = ANY;
6097
+ } else {
6098
+ this.semver = new SemVer(m[2], this.options.loose);
6099
+ }
6100
+ }
6101
+ toString() {
6102
+ return this.value;
6103
+ }
6104
+ test(version) {
6105
+ debug("Comparator.test", version, this.options.loose);
6106
+ if (this.semver === ANY || version === ANY) {
6107
+ return true;
6108
+ }
6109
+ if (typeof version === "string") {
6110
+ try {
6111
+ version = new SemVer(version, this.options);
6112
+ } catch (er) {
6113
+ return false;
6114
+ }
6115
+ }
6116
+ return cmp(version, this.operator, this.semver, this.options);
6117
+ }
6118
+ intersects(comp, options) {
6119
+ if (!(comp instanceof _Comparator)) {
6120
+ throw new TypeError("a Comparator is required");
6121
+ }
6122
+ if (this.operator === "") {
6123
+ if (this.value === "") {
6124
+ return true;
6125
+ }
6126
+ return new Range(comp.value, options).test(this.value);
6127
+ } else if (comp.operator === "") {
6128
+ if (comp.value === "") {
6129
+ return true;
6130
+ }
6131
+ return new Range(this.value, options).test(comp.semver);
6132
+ }
6133
+ options = parseOptions(options);
6134
+ if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) {
6135
+ return false;
6136
+ }
6137
+ if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) {
6138
+ return false;
6139
+ }
6140
+ if (this.operator.startsWith(">") && comp.operator.startsWith(">")) {
6141
+ return true;
6142
+ }
6143
+ if (this.operator.startsWith("<") && comp.operator.startsWith("<")) {
6144
+ return true;
6145
+ }
6146
+ if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) {
6147
+ return true;
6148
+ }
6149
+ if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
6150
+ return true;
6151
+ }
6152
+ if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
6153
+ return true;
6154
+ }
6155
+ return false;
6156
+ }
6157
+ };
6158
+ module.exports = Comparator;
6159
+ var parseOptions = require_parse_options();
6160
+ var { safeRe: re, t } = require_re();
6161
+ var cmp = require_cmp();
6162
+ var debug = require_debug();
6163
+ var SemVer = require_semver();
6164
+ var Range = require_range();
6165
+ }
6166
+ });
6167
+
6168
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/satisfies.js
6169
+ var require_satisfies = __commonJS({
6170
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/satisfies.js"(exports, module) {
6171
+ "use strict";
6172
+ var Range = require_range();
6173
+ var satisfies = (version, range, options) => {
6174
+ try {
6175
+ range = new Range(range, options);
6176
+ } catch (er) {
6177
+ return false;
6178
+ }
6179
+ return range.test(version);
6180
+ };
6181
+ module.exports = satisfies;
6182
+ }
6183
+ });
6184
+
6185
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/to-comparators.js
6186
+ var require_to_comparators = __commonJS({
6187
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/to-comparators.js"(exports, module) {
6188
+ "use strict";
6189
+ var Range = require_range();
6190
+ var toComparators = (range, options) => new Range(range, options).set.map((comp) => comp.map((c) => c.value).join(" ").trim().split(" "));
6191
+ module.exports = toComparators;
6192
+ }
6193
+ });
6194
+
6195
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/max-satisfying.js
6196
+ var require_max_satisfying = __commonJS({
6197
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/max-satisfying.js"(exports, module) {
6198
+ "use strict";
6199
+ var SemVer = require_semver();
6200
+ var Range = require_range();
6201
+ var maxSatisfying = (versions, range, options) => {
6202
+ let max = null;
6203
+ let maxSV = null;
6204
+ let rangeObj = null;
6205
+ try {
6206
+ rangeObj = new Range(range, options);
6207
+ } catch (er) {
6208
+ return null;
6209
+ }
6210
+ versions.forEach((v) => {
6211
+ if (rangeObj.test(v)) {
6212
+ if (!max || maxSV.compare(v) === -1) {
6213
+ max = v;
6214
+ maxSV = new SemVer(max, options);
6215
+ }
6216
+ }
6217
+ });
6218
+ return max;
6219
+ };
6220
+ module.exports = maxSatisfying;
6221
+ }
6222
+ });
6223
+
6224
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/min-satisfying.js
6225
+ var require_min_satisfying = __commonJS({
6226
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/min-satisfying.js"(exports, module) {
6227
+ "use strict";
6228
+ var SemVer = require_semver();
6229
+ var Range = require_range();
6230
+ var minSatisfying = (versions, range, options) => {
6231
+ let min = null;
6232
+ let minSV = null;
6233
+ let rangeObj = null;
6234
+ try {
6235
+ rangeObj = new Range(range, options);
6236
+ } catch (er) {
6237
+ return null;
6238
+ }
6239
+ versions.forEach((v) => {
6240
+ if (rangeObj.test(v)) {
6241
+ if (!min || minSV.compare(v) === 1) {
6242
+ min = v;
6243
+ minSV = new SemVer(min, options);
6244
+ }
6245
+ }
6246
+ });
6247
+ return min;
6248
+ };
6249
+ module.exports = minSatisfying;
6250
+ }
6251
+ });
6252
+
6253
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/min-version.js
6254
+ var require_min_version = __commonJS({
6255
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/min-version.js"(exports, module) {
6256
+ "use strict";
6257
+ var SemVer = require_semver();
6258
+ var Range = require_range();
6259
+ var gt = require_gt();
6260
+ var minVersion = (range, loose) => {
6261
+ range = new Range(range, loose);
6262
+ let minver = new SemVer("0.0.0");
6263
+ if (range.test(minver)) {
6264
+ return minver;
6265
+ }
6266
+ minver = new SemVer("0.0.0-0");
6267
+ if (range.test(minver)) {
6268
+ return minver;
6269
+ }
6270
+ minver = null;
6271
+ for (let i = 0; i < range.set.length; ++i) {
6272
+ const comparators = range.set[i];
6273
+ let setMin = null;
6274
+ comparators.forEach((comparator) => {
6275
+ const compver = new SemVer(comparator.semver.version);
6276
+ switch (comparator.operator) {
6277
+ case ">":
6278
+ if (compver.prerelease.length === 0) {
6279
+ compver.patch++;
6280
+ } else {
6281
+ compver.prerelease.push(0);
6282
+ }
6283
+ compver.raw = compver.format();
6284
+ /* fallthrough */
6285
+ case "":
6286
+ case ">=":
6287
+ if (!setMin || gt(compver, setMin)) {
6288
+ setMin = compver;
6289
+ }
6290
+ break;
6291
+ case "<":
6292
+ case "<=":
6293
+ break;
6294
+ /* istanbul ignore next */
6295
+ default:
6296
+ throw new Error(`Unexpected operation: ${comparator.operator}`);
6297
+ }
6298
+ });
6299
+ if (setMin && (!minver || gt(minver, setMin))) {
6300
+ minver = setMin;
6301
+ }
6302
+ }
6303
+ if (minver && range.test(minver)) {
6304
+ return minver;
6305
+ }
6306
+ return null;
6307
+ };
6308
+ module.exports = minVersion;
6309
+ }
6310
+ });
6311
+
6312
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/valid.js
6313
+ var require_valid2 = __commonJS({
6314
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/valid.js"(exports, module) {
6315
+ "use strict";
6316
+ var Range = require_range();
6317
+ var validRange = (range, options) => {
6318
+ try {
6319
+ return new Range(range, options).range || "*";
6320
+ } catch (er) {
6321
+ return null;
6322
+ }
6323
+ };
6324
+ module.exports = validRange;
6325
+ }
6326
+ });
6327
+
6328
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/outside.js
6329
+ var require_outside = __commonJS({
6330
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/outside.js"(exports, module) {
6331
+ "use strict";
6332
+ var SemVer = require_semver();
6333
+ var Comparator = require_comparator();
6334
+ var { ANY } = Comparator;
6335
+ var Range = require_range();
6336
+ var satisfies = require_satisfies();
6337
+ var gt = require_gt();
6338
+ var lt = require_lt();
6339
+ var lte = require_lte();
6340
+ var gte = require_gte();
6341
+ var outside = (version, range, hilo, options) => {
6342
+ version = new SemVer(version, options);
6343
+ range = new Range(range, options);
6344
+ let gtfn, ltefn, ltfn, comp, ecomp;
6345
+ switch (hilo) {
6346
+ case ">":
6347
+ gtfn = gt;
6348
+ ltefn = lte;
6349
+ ltfn = lt;
6350
+ comp = ">";
6351
+ ecomp = ">=";
6352
+ break;
6353
+ case "<":
6354
+ gtfn = lt;
6355
+ ltefn = gte;
6356
+ ltfn = gt;
6357
+ comp = "<";
6358
+ ecomp = "<=";
6359
+ break;
6360
+ default:
6361
+ throw new TypeError('Must provide a hilo val of "<" or ">"');
6362
+ }
6363
+ if (satisfies(version, range, options)) {
6364
+ return false;
6365
+ }
6366
+ for (let i = 0; i < range.set.length; ++i) {
6367
+ const comparators = range.set[i];
6368
+ let high = null;
6369
+ let low = null;
6370
+ comparators.forEach((comparator) => {
6371
+ if (comparator.semver === ANY) {
6372
+ comparator = new Comparator(">=0.0.0");
6373
+ }
6374
+ high = high || comparator;
6375
+ low = low || comparator;
6376
+ if (gtfn(comparator.semver, high.semver, options)) {
6377
+ high = comparator;
6378
+ } else if (ltfn(comparator.semver, low.semver, options)) {
6379
+ low = comparator;
6380
+ }
6381
+ });
6382
+ if (high.operator === comp || high.operator === ecomp) {
6383
+ return false;
6384
+ }
6385
+ if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
6386
+ return false;
6387
+ } else if (low.operator === ecomp && ltfn(version, low.semver)) {
6388
+ return false;
6389
+ }
6390
+ }
6391
+ return true;
6392
+ };
6393
+ module.exports = outside;
6394
+ }
6395
+ });
6396
+
6397
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/gtr.js
6398
+ var require_gtr = __commonJS({
6399
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/gtr.js"(exports, module) {
6400
+ "use strict";
6401
+ var outside = require_outside();
6402
+ var gtr = (version, range, options) => outside(version, range, ">", options);
6403
+ module.exports = gtr;
6404
+ }
6405
+ });
6406
+
6407
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/ltr.js
6408
+ var require_ltr = __commonJS({
6409
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/ltr.js"(exports, module) {
6410
+ "use strict";
6411
+ var outside = require_outside();
6412
+ var ltr = (version, range, options) => outside(version, range, "<", options);
6413
+ module.exports = ltr;
6414
+ }
6415
+ });
6416
+
6417
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/intersects.js
6418
+ var require_intersects = __commonJS({
6419
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/intersects.js"(exports, module) {
6420
+ "use strict";
6421
+ var Range = require_range();
6422
+ var intersects = (r1, r2, options) => {
6423
+ r1 = new Range(r1, options);
6424
+ r2 = new Range(r2, options);
6425
+ return r1.intersects(r2, options);
6426
+ };
6427
+ module.exports = intersects;
6428
+ }
6429
+ });
6430
+
6431
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/simplify.js
6432
+ var require_simplify = __commonJS({
6433
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/simplify.js"(exports, module) {
6434
+ "use strict";
6435
+ var satisfies = require_satisfies();
6436
+ var compare = require_compare();
6437
+ module.exports = (versions, range, options) => {
6438
+ const set = [];
6439
+ let first = null;
6440
+ let prev = null;
6441
+ const v = versions.sort((a, b) => compare(a, b, options));
6442
+ for (const version of v) {
6443
+ const included = satisfies(version, range, options);
6444
+ if (included) {
6445
+ prev = version;
6446
+ if (!first) {
6447
+ first = version;
6448
+ }
6449
+ } else {
6450
+ if (prev) {
6451
+ set.push([first, prev]);
6452
+ }
6453
+ prev = null;
6454
+ first = null;
6455
+ }
6456
+ }
6457
+ if (first) {
6458
+ set.push([first, null]);
6459
+ }
6460
+ const ranges = [];
6461
+ for (const [min, max] of set) {
6462
+ if (min === max) {
6463
+ ranges.push(min);
6464
+ } else if (!max && min === v[0]) {
6465
+ ranges.push("*");
6466
+ } else if (!max) {
6467
+ ranges.push(`>=${min}`);
6468
+ } else if (min === v[0]) {
6469
+ ranges.push(`<=${max}`);
6470
+ } else {
6471
+ ranges.push(`${min} - ${max}`);
6472
+ }
6473
+ }
6474
+ const simplified = ranges.join(" || ");
6475
+ const original = typeof range.raw === "string" ? range.raw : String(range);
6476
+ return simplified.length < original.length ? simplified : range;
6477
+ };
6478
+ }
6479
+ });
6480
+
6481
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/subset.js
6482
+ var require_subset = __commonJS({
6483
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/subset.js"(exports, module) {
6484
+ "use strict";
6485
+ var Range = require_range();
6486
+ var Comparator = require_comparator();
6487
+ var { ANY } = Comparator;
6488
+ var satisfies = require_satisfies();
6489
+ var compare = require_compare();
6490
+ var subset = (sub, dom, options = {}) => {
6491
+ if (sub === dom) {
6492
+ return true;
6493
+ }
6494
+ sub = new Range(sub, options);
6495
+ dom = new Range(dom, options);
6496
+ let sawNonNull = false;
6497
+ OUTER: for (const simpleSub of sub.set) {
6498
+ for (const simpleDom of dom.set) {
6499
+ const isSub = simpleSubset(simpleSub, simpleDom, options);
6500
+ sawNonNull = sawNonNull || isSub !== null;
6501
+ if (isSub) {
6502
+ continue OUTER;
6503
+ }
6504
+ }
6505
+ if (sawNonNull) {
6506
+ return false;
6507
+ }
6508
+ }
6509
+ return true;
6510
+ };
6511
+ var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")];
6512
+ var minimumVersion = [new Comparator(">=0.0.0")];
6513
+ var simpleSubset = (sub, dom, options) => {
6514
+ if (sub === dom) {
6515
+ return true;
6516
+ }
6517
+ if (sub.length === 1 && sub[0].semver === ANY) {
6518
+ if (dom.length === 1 && dom[0].semver === ANY) {
6519
+ return true;
6520
+ } else if (options.includePrerelease) {
6521
+ sub = minimumVersionWithPreRelease;
6522
+ } else {
6523
+ sub = minimumVersion;
6524
+ }
6525
+ }
6526
+ if (dom.length === 1 && dom[0].semver === ANY) {
6527
+ if (options.includePrerelease) {
6528
+ return true;
6529
+ } else {
6530
+ dom = minimumVersion;
6531
+ }
6532
+ }
6533
+ const eqSet = /* @__PURE__ */ new Set();
6534
+ let gt, lt;
6535
+ for (const c of sub) {
6536
+ if (c.operator === ">" || c.operator === ">=") {
6537
+ gt = higherGT(gt, c, options);
6538
+ } else if (c.operator === "<" || c.operator === "<=") {
6539
+ lt = lowerLT(lt, c, options);
6540
+ } else {
6541
+ eqSet.add(c.semver);
6542
+ }
6543
+ }
6544
+ if (eqSet.size > 1) {
6545
+ return null;
6546
+ }
6547
+ let gtltComp;
6548
+ if (gt && lt) {
6549
+ gtltComp = compare(gt.semver, lt.semver, options);
6550
+ if (gtltComp > 0) {
6551
+ return null;
6552
+ } else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<=")) {
6553
+ return null;
6554
+ }
6555
+ }
6556
+ for (const eq of eqSet) {
6557
+ if (gt && !satisfies(eq, String(gt), options)) {
6558
+ return null;
6559
+ }
6560
+ if (lt && !satisfies(eq, String(lt), options)) {
6561
+ return null;
6562
+ }
6563
+ for (const c of dom) {
6564
+ if (!satisfies(eq, String(c), options)) {
6565
+ return false;
6566
+ }
6567
+ }
6568
+ return true;
6569
+ }
6570
+ let higher, lower;
6571
+ let hasDomLT, hasDomGT;
6572
+ let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false;
6573
+ let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false;
6574
+ if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === "<" && needDomLTPre.prerelease[0] === 0) {
6575
+ needDomLTPre = false;
6576
+ }
6577
+ for (const c of dom) {
6578
+ hasDomGT = hasDomGT || c.operator === ">" || c.operator === ">=";
6579
+ hasDomLT = hasDomLT || c.operator === "<" || c.operator === "<=";
6580
+ if (gt) {
6581
+ if (needDomGTPre) {
6582
+ if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) {
6583
+ needDomGTPre = false;
6584
+ }
6585
+ }
6586
+ if (c.operator === ">" || c.operator === ">=") {
6587
+ higher = higherGT(gt, c, options);
6588
+ if (higher === c && higher !== gt) {
6589
+ return false;
6590
+ }
6591
+ } else if (gt.operator === ">=" && !c.test(gt.semver)) {
6592
+ return false;
6593
+ }
6594
+ }
6595
+ if (lt) {
6596
+ if (needDomLTPre) {
6597
+ if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) {
6598
+ needDomLTPre = false;
6599
+ }
6600
+ }
6601
+ if (c.operator === "<" || c.operator === "<=") {
6602
+ lower = lowerLT(lt, c, options);
6603
+ if (lower === c && lower !== lt) {
6604
+ return false;
6605
+ }
6606
+ } else if (lt.operator === "<=" && !c.test(lt.semver)) {
6607
+ return false;
6608
+ }
6609
+ }
6610
+ if (!c.operator && (lt || gt) && gtltComp !== 0) {
6611
+ return false;
6612
+ }
6613
+ }
6614
+ if (gt && hasDomLT && !lt && gtltComp !== 0) {
6615
+ return false;
6616
+ }
6617
+ if (lt && hasDomGT && !gt && gtltComp !== 0) {
6618
+ return false;
6619
+ }
6620
+ if (needDomGTPre || needDomLTPre) {
6621
+ return false;
6622
+ }
6623
+ return true;
6624
+ };
6625
+ var higherGT = (a, b, options) => {
6626
+ if (!a) {
6627
+ return b;
6628
+ }
6629
+ const comp = compare(a.semver, b.semver, options);
6630
+ return comp > 0 ? a : comp < 0 ? b : b.operator === ">" && a.operator === ">=" ? b : a;
6631
+ };
6632
+ var lowerLT = (a, b, options) => {
6633
+ if (!a) {
6634
+ return b;
6635
+ }
6636
+ const comp = compare(a.semver, b.semver, options);
6637
+ return comp < 0 ? a : comp > 0 ? b : b.operator === "<" && a.operator === "<=" ? b : a;
6638
+ };
6639
+ module.exports = subset;
6640
+ }
6641
+ });
6642
+
6643
+ // ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/index.js
6644
+ var require_semver2 = __commonJS({
6645
+ "../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/index.js"(exports, module) {
6646
+ "use strict";
6647
+ var internalRe = require_re();
6648
+ var constants3 = require_constants();
6649
+ var SemVer = require_semver();
6650
+ var identifiers = require_identifiers();
6651
+ var parse = require_parse();
6652
+ var valid = require_valid();
6653
+ var clean = require_clean();
6654
+ var inc = require_inc();
6655
+ var diff = require_diff();
6656
+ var major = require_major();
6657
+ var minor = require_minor();
6658
+ var patch = require_patch();
6659
+ var prerelease = require_prerelease();
6660
+ var compare = require_compare();
6661
+ var rcompare = require_rcompare();
6662
+ var compareLoose = require_compare_loose();
6663
+ var compareBuild = require_compare_build();
6664
+ var sort = require_sort();
6665
+ var rsort = require_rsort();
6666
+ var gt = require_gt();
6667
+ var lt = require_lt();
6668
+ var eq = require_eq();
6669
+ var neq = require_neq();
6670
+ var gte = require_gte();
6671
+ var lte = require_lte();
6672
+ var cmp = require_cmp();
6673
+ var coerce = require_coerce();
6674
+ var truncate = require_truncate();
6675
+ var Comparator = require_comparator();
6676
+ var Range = require_range();
6677
+ var satisfies = require_satisfies();
6678
+ var toComparators = require_to_comparators();
6679
+ var maxSatisfying = require_max_satisfying();
6680
+ var minSatisfying = require_min_satisfying();
6681
+ var minVersion = require_min_version();
6682
+ var validRange = require_valid2();
6683
+ var outside = require_outside();
6684
+ var gtr = require_gtr();
6685
+ var ltr = require_ltr();
6686
+ var intersects = require_intersects();
6687
+ var simplifyRange = require_simplify();
6688
+ var subset = require_subset();
6689
+ module.exports = {
6690
+ parse,
6691
+ valid,
6692
+ clean,
6693
+ inc,
6694
+ diff,
6695
+ major,
6696
+ minor,
6697
+ patch,
6698
+ prerelease,
6699
+ compare,
6700
+ rcompare,
6701
+ compareLoose,
6702
+ compareBuild,
6703
+ sort,
6704
+ rsort,
6705
+ gt,
6706
+ lt,
6707
+ eq,
6708
+ neq,
6709
+ gte,
6710
+ lte,
6711
+ cmp,
6712
+ coerce,
6713
+ truncate,
6714
+ Comparator,
6715
+ Range,
6716
+ satisfies,
6717
+ toComparators,
6718
+ maxSatisfying,
6719
+ minSatisfying,
6720
+ minVersion,
6721
+ validRange,
6722
+ outside,
6723
+ gtr,
6724
+ ltr,
6725
+ intersects,
6726
+ simplifyRange,
6727
+ subset,
6728
+ SemVer,
6729
+ re: internalRe.re,
6730
+ src: internalRe.src,
6731
+ tokens: internalRe.t,
6732
+ SEMVER_SPEC_VERSION: constants3.SEMVER_SPEC_VERSION,
6733
+ RELEASE_TYPES: constants3.RELEASE_TYPES,
6734
+ compareIdentifiers: identifiers.compareIdentifiers,
6735
+ rcompareIdentifiers: identifiers.rcompareIdentifiers
6736
+ };
6737
+ }
6738
+ });
6739
+
6740
+ // ../core/dist/module-permissions.js
6741
+ import { realpathSync } from "node:fs";
6742
+ import { basename as basename3, dirname as dirname6, join as join14, resolve as resolve4, sep as sep2 } from "node:path";
6743
+ function expandGrants(permissions, settings) {
6744
+ const p = permissions ?? {};
6745
+ return {
6746
+ network: expandAll(p.network, settings, "origin").map(normalizeOrigin).filter((o) => o !== null),
6747
+ fsRead: expandAll(p["fs:read"], settings, "path").map(expandHome),
6748
+ fsWrite: expandAll(p["fs:write"], settings, "path").map(expandHome),
6749
+ shell: expandAll(p.shell, settings, "path").map(expandHome),
6750
+ pty: p.pty === true
6751
+ };
6752
+ }
6753
+ function expandAll(templates, settings, kind) {
6754
+ return (templates ?? []).flatMap((t) => expandOne(t, settings, kind));
6755
+ }
6756
+ function safeValue(value, kind, atStart) {
6757
+ if (kind === "origin")
6758
+ return !/[/?#@\\\s]/.test(value);
6759
+ return atStart || !value.split(/[/\\]/).includes("..");
6760
+ }
6761
+ function expandOne(template, settings, kind) {
6762
+ const lists = /* @__PURE__ */ new Set();
6763
+ for (const m of template.matchAll(TEMPLATE_RE))
6764
+ if (m[2])
6765
+ lists.add(m[1]);
6766
+ if (lists.size > 1)
6767
+ return [];
6768
+ const [list] = [...lists];
6769
+ const items = list ? Array.isArray(settings[list]) ? settings[list].map((i) => typeof i === "object" && i !== null ? i : {}) : [] : [void 0];
6770
+ const out = [];
6771
+ for (const item of items) {
6772
+ let missing = false;
6773
+ const text = template.replace(TEMPLATE_RE, (_all, key, isList, field, offset) => {
6774
+ const v = isList ? item?.[field] : settings[key];
6775
+ const s = typeof v === "string" ? v : typeof v === "number" && Number.isFinite(v) ? String(v) : "";
6776
+ if (s && safeValue(s, kind, offset === 0))
6777
+ return s;
6778
+ missing = true;
6779
+ return "";
6780
+ });
6781
+ if (!missing)
6782
+ out.push(text);
6783
+ }
6784
+ return out;
6785
+ }
6786
+ function normalizeOrigin(value) {
6787
+ try {
6788
+ const url = new URL(value);
6789
+ return url.username || url.password ? null : url.origin;
6790
+ } catch {
6791
+ return null;
6792
+ }
6793
+ }
6794
+ function allowsOrigin(grants, target) {
6795
+ try {
6796
+ const url = new URL(target);
6797
+ if (url.username || url.password)
6798
+ return false;
6799
+ return grants.network.includes(url.origin);
6800
+ } catch {
6801
+ return false;
6802
+ }
6803
+ }
6804
+ function allowsCommand(grants, command) {
6805
+ return grants.shell.includes(expandHome(command));
6806
+ }
6807
+ async function allowsPath(grants, target) {
6808
+ const real = realOrParent(resolve4(expandHome(target)));
6809
+ for (const grant of grants) {
6810
+ const folder = grant.endsWith("/");
6811
+ const base = realOrParent(resolve4(expandHome(grant)));
6812
+ if (folder ? real === base || real.startsWith(base + sep2) : real === base)
6813
+ return true;
6814
+ }
6815
+ return false;
6816
+ }
6817
+ function realOrParent(path) {
6818
+ try {
6819
+ return realpathSync(path);
6820
+ } catch {
6821
+ const parent = dirname6(path);
6822
+ return parent === path ? path : join14(realOrParent(parent), basename3(path));
6823
+ }
6824
+ }
6825
+ var TEMPLATE_RE;
6826
+ var init_module_permissions = __esm({
6827
+ "../core/dist/module-permissions.js"() {
6828
+ "use strict";
6829
+ init_state_log();
6830
+ TEMPLATE_RE = /\{([a-zA-Z0-9_]+)(\[\]\.([a-zA-Z0-9_]+))?\}/g;
6831
+ }
6832
+ });
6833
+
6834
+ // ../core/dist/module-manifest.js
6835
+ import { readFileSync as readFileSync10 } from "node:fs";
6836
+ import { join as join15, resolve as resolve5, sep as sep3 } from "node:path";
6837
+ function checkSdk(range, version = SDK_VERSION) {
6838
+ if (!import_semver.default.validRange(range))
6839
+ return `sdk range "${range}" is not valid semver`;
6840
+ return import_semver.default.satisfies(version, range) ? null : `needs SDK ${range}, Forge has ${version}`;
6841
+ }
6842
+ function checkManifest(raw, moduleDir) {
6843
+ if (!isObject(raw))
6844
+ return { kind: "invalid", reason: "/: must be an object" };
6845
+ if (raw.sdk === void 0) {
6846
+ if (V1_FIELDS.some((f) => raw[f] !== void 0))
6847
+ return { kind: "invalid", reason: "declares v1 fields but no sdk range" };
6848
+ return { kind: "legacy", manifest: raw };
6849
+ }
6850
+ const errors = [];
6851
+ const err = (path, message) => errors.push(`${path}: ${message}`);
6852
+ for (const key of Object.keys(raw))
6853
+ if (!TOP_LEVEL.has(key))
6854
+ err(`/${key}`, "unknown field");
6855
+ for (const key of ["id", "name", "version", "sdk", "displayName"]) {
6856
+ if (typeof raw[key] !== "string" || raw[key] === "")
6857
+ err(`/${key}`, "required string");
6858
+ }
6859
+ if (typeof raw.id === "string" && !MODULE_ID_RE.test(raw.id))
6860
+ err("/id", `must match ${MODULE_ID_RE.source}`);
6861
+ for (const key of ["description", "icon", "color", "server"]) {
6862
+ if (raw[key] !== void 0 && typeof raw[key] !== "string")
6863
+ err(`/${key}`, "must be a string");
6864
+ }
6865
+ if (raw.view !== void 0) {
6866
+ if (!isObject(raw.view) || typeof raw.view.entry !== "string" || raw.view.entry === "")
6867
+ err("/view/entry", "required string");
6868
+ else if (raw.view.title !== void 0 && typeof raw.view.title !== "string")
6869
+ err("/view/title", "must be a string");
6870
+ }
6871
+ if (raw.permissions !== void 0) {
6872
+ if (!isObject(raw.permissions))
6873
+ err("/permissions", "must be an object");
6874
+ else {
6875
+ for (const [key, value] of Object.entries(raw.permissions)) {
6876
+ if (!PERMISSIONS.has(key))
6877
+ err(`/permissions/${key}`, "unknown permission");
6878
+ else if (key === "pty" ? typeof value !== "boolean" : !isStringArray(value)) {
6879
+ err(`/permissions/${key}`, key === "pty" ? "must be a boolean" : "must be a list of strings");
6880
+ }
6881
+ }
6882
+ }
6883
+ }
6884
+ if (raw.settings !== void 0) {
6885
+ if (!isObject(raw.settings) || !isObject(raw.settings.schema))
6886
+ err("/settings/schema", "required object");
6887
+ else
6888
+ for (const [key, def] of Object.entries(raw.settings.schema))
6889
+ checkSettingDef(def, `/settings/schema/${key}`, true, err);
6890
+ }
6891
+ for (const key of ["actions", "detectors", "panels"]) {
6892
+ if (raw[key] !== void 0 && !Array.isArray(raw[key]))
6893
+ err(`/${key}`, "must be a list");
6894
+ }
6895
+ if (typeof raw.sdk === "string" && errors.length === 0) {
6896
+ const sdkReason = checkSdk(raw.sdk);
6897
+ if (sdkReason)
6898
+ return { kind: "invalid", reason: sdkReason };
6899
+ }
6900
+ if (errors.length === 0) {
6901
+ const entries = [["/server", raw.server], ["/view/entry", isObject(raw.view) ? raw.view.entry : void 0]];
6902
+ for (const [path, value] of entries) {
6903
+ if (typeof value === "string" && !insideFolder(moduleDir, value))
6904
+ err(path, "points outside the module folder");
6905
+ }
6906
+ }
6907
+ if (errors.length > 0)
6908
+ return { kind: "invalid", reason: errors.join("; ") };
6909
+ return { kind: "v1", manifest: raw };
6910
+ }
6911
+ function checkSettingDef(def, path, allowList, err) {
6912
+ if (!isObject(def))
6913
+ return err(path, "must be an object");
6914
+ if (def.type === "list") {
6915
+ if (!allowList)
6916
+ return err(`${path}/type`, "lists do not nest");
6917
+ if (!isObject(def.item))
6918
+ return err(`${path}/item`, "required object");
6919
+ for (const [key, sub] of Object.entries(def.item))
6920
+ checkSettingDef(sub, `${path}/item/${key}`, false, err);
6921
+ return;
6922
+ }
6923
+ if (typeof def.type !== "string" || !SCALAR_TYPES.has(def.type))
6924
+ return err(`${path}/type`, "must be string, number, boolean, enum or list");
6925
+ if (def.type === "enum" && !isStringArray(def.values))
6926
+ err(`${path}/values`, "required list of strings");
6927
+ if (def.format !== void 0 && !FORMATS.has(def.format))
6928
+ err(`${path}/format`, "must be path, cw-project or url");
6929
+ if (def.pattern !== void 0) {
6930
+ try {
6931
+ new RegExp(def.pattern);
6932
+ } catch {
6933
+ err(`${path}/pattern`, "is not a valid regular expression");
6934
+ }
6935
+ }
6936
+ }
6937
+ function insideFolder(dir, relative) {
6938
+ const root = realOrParent(resolve5(dir));
6939
+ const target = realOrParent(resolve5(dir, relative));
6940
+ return target === root || target.startsWith(root + sep3);
6941
+ }
6942
+ function manifestFileFor(dir) {
6943
+ try {
6944
+ const pkg = JSON.parse(readFileSync10(join15(dir, "package.json"), "utf-8"));
6945
+ const manifest = typeof pkg.forge?.manifest === "string" ? pkg.forge.manifest : "forge-module.json";
6946
+ return { file: join15(dir, manifest), hasForgeField: pkg.forge !== void 0 };
6947
+ } catch {
6948
+ return { file: join15(dir, "forge-module.json"), hasForgeField: false };
6949
+ }
6950
+ }
6951
+ function validateSettings(schema, values) {
6952
+ const input = isObject(values) ? values : {};
6953
+ const errors = [];
6954
+ const value = {};
6955
+ for (const [key, def] of Object.entries(schema)) {
6956
+ if (def.type === "list") {
6957
+ const raw = input[key] ?? def.default ?? [];
6958
+ if (!Array.isArray(raw)) {
6959
+ errors.push({ path: key, message: "must be a list" });
6960
+ continue;
6961
+ }
6962
+ value[key] = raw.map((item, i) => {
6963
+ const obj2 = isObject(item) ? item : {};
6964
+ if (!isObject(item))
6965
+ errors.push({ path: `${key}[${i}]`, message: "must be an object" });
6966
+ const out = {};
6967
+ for (const [field, sub] of Object.entries(def.item)) {
6968
+ const v = scalar(sub, obj2[field], `${key}[${i}].${field}`, errors);
6969
+ if (v !== void 0)
6970
+ out[field] = v;
6971
+ }
6972
+ return out;
6973
+ });
6974
+ } else {
6975
+ const v = scalar(def, input[key], key, errors);
6976
+ if (v !== void 0)
6977
+ value[key] = v;
6978
+ }
6979
+ }
6980
+ return errors.length > 0 ? { ok: false, errors } : { ok: true, value };
6981
+ }
6982
+ function scalar(def, raw, path, errors) {
6983
+ const v = raw === void 0 || raw === "" ? def.default : raw;
6984
+ if (v === void 0) {
6985
+ if (def.required)
6986
+ errors.push({ path, message: "required" });
6987
+ return void 0;
6988
+ }
6989
+ const fail = (message) => {
6990
+ errors.push({ path, message });
6991
+ return void 0;
6992
+ };
6993
+ switch (def.type) {
6994
+ case "string":
6995
+ if (typeof v !== "string")
6996
+ return fail("must be a string");
6997
+ if (def.pattern && !new RegExp(def.pattern).test(v))
6998
+ return fail(`must match ${def.pattern}`);
6999
+ return v;
7000
+ case "number":
7001
+ if (typeof v !== "number" || !Number.isFinite(v))
7002
+ return fail("must be a number");
7003
+ if (def.min !== void 0 && v < def.min)
7004
+ return fail(`must be at least ${def.min}`);
7005
+ if (def.max !== void 0 && v > def.max)
7006
+ return fail(`must be at most ${def.max}`);
7007
+ return v;
7008
+ case "boolean":
7009
+ return typeof v === "boolean" ? v : fail("must be a boolean");
7010
+ case "enum":
7011
+ return typeof v === "string" && def.values.includes(v) ? v : fail(`must be one of ${def.values.join(", ")}`);
7012
+ }
7013
+ }
7014
+ var import_semver, V1_FIELDS, TOP_LEVEL, PERMISSIONS, SCALAR_TYPES, FORMATS, isObject, isStringArray;
7015
+ var init_module_manifest = __esm({
7016
+ "../core/dist/module-manifest.js"() {
7017
+ "use strict";
7018
+ import_semver = __toESM(require_semver2(), 1);
7019
+ init_dist();
7020
+ init_module_permissions();
7021
+ V1_FIELDS = ["server", "view", "permissions", "id"];
7022
+ TOP_LEVEL = /* @__PURE__ */ new Set(["$schema", "id", "name", "version", "sdk", "displayName", "description", "icon", "color", "server", "view", "permissions", "settings", "actions", "detectors", "panels", "claude"]);
7023
+ PERMISSIONS = /* @__PURE__ */ new Set(["network", "fs:read", "fs:write", "shell", "pty"]);
7024
+ SCALAR_TYPES = /* @__PURE__ */ new Set(["string", "number", "boolean", "enum"]);
7025
+ FORMATS = /* @__PURE__ */ new Set(["path", "cw-project", "url"]);
7026
+ isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
7027
+ isStringArray = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
7028
+ }
7029
+ });
7030
+
7031
+ // ../core/dist/module-context.js
7032
+ import { readFile, readdir, writeFile } from "node:fs/promises";
7033
+ import { homedir as homedir6 } from "node:os";
7034
+ function createForgeContext(deps, mod, getSettings, getGrants, onDenial) {
7035
+ const doFetch = deps.fetch ?? globalThis.fetch;
7036
+ const log = deps.log ?? console;
7037
+ const deny = (permission, value) => {
7038
+ onDenial(permission, value);
7039
+ throw new PermissionError(permission, value);
7040
+ };
7041
+ const checkPath = async (permission, path) => {
7042
+ const list = permission === "fs:read" ? getGrants().fsRead : getGrants().fsWrite;
7043
+ if (!await allowsPath(list, path))
7044
+ deny(permission, path);
7045
+ };
7046
+ const prefix = `[module ${mod.id}]`;
7047
+ return {
7048
+ module: mod,
7049
+ get settings() {
7050
+ return getSettings();
7051
+ },
7052
+ sessions: {
7053
+ list: async () => deps.reader.getSpaces().map(toSessionInfo)
7054
+ },
7055
+ projects: {
7056
+ list: async () => Object.entries(deps.reader.getProjects()).map(([name, p]) => ({ name, path: p.path, account: p.account })),
7057
+ dir: async (name) => deps.reader.getProjects()[name]?.path ?? null
7058
+ },
7059
+ accounts: {
7060
+ list: async () => deps.reader.getAccounts().map((name) => ({ name }))
7061
+ },
7062
+ git: {
7063
+ status: async (project, sessionDir) => {
7064
+ const session = deps.reader.getSession(project, sessionDir);
7065
+ if (!session?.worktree)
7066
+ return { files: [] };
7067
+ const result2 = await deps.runner.spawn("git", ["status", "--porcelain=v1", "-b"], { cwd: session.worktree, timeout: 1e4 });
7068
+ return result2.exitCode === 0 ? parseGitStatus(result2.output) : { files: [] };
7069
+ }
7070
+ },
7071
+ storage: {
7072
+ get: async (key) => {
7073
+ const raw = deps.db.kvGet(mod.id, key);
7074
+ return raw === void 0 ? void 0 : JSON.parse(raw);
7075
+ },
7076
+ set: async (key, value) => deps.db.kvSet(mod.id, key, JSON.stringify(value)),
7077
+ delete: async (key) => deps.db.kvDelete(mod.id, key),
7078
+ list: async (p) => deps.db.kvList(mod.id, p)
7079
+ },
7080
+ notify: {
7081
+ attention: async (n) => {
7082
+ deps.db.upsertNotification({ moduleId: mod.id, key: n.key, kind: "attention", title: n.title, body: n.body, version: n.version });
7083
+ },
7084
+ badge: async (key, count, label) => {
7085
+ if (count <= 0)
7086
+ return deps.db.deleteNotification(mod.id, key);
7087
+ deps.db.upsertNotification({ moduleId: mod.id, key, kind: "badge", title: label ?? "", count, label });
7088
+ },
7089
+ clear: async (key) => deps.db.deleteNotification(mod.id, key)
7090
+ },
7091
+ fetch: async (url, init) => {
7092
+ if (!allowsOrigin(getGrants(), url))
7093
+ deny("network", url);
7094
+ return doFetch(url, init);
7095
+ },
7096
+ fs: {
7097
+ read: async (path) => {
7098
+ await checkPath("fs:read", path);
7099
+ return readFile(expandHome(path), "utf-8");
7100
+ },
7101
+ list: async (dir) => {
7102
+ await checkPath("fs:read", dir.endsWith("/") ? dir : dir + "/");
7103
+ return readdir(expandHome(dir));
7104
+ },
7105
+ write: async (path, data) => {
7106
+ await checkPath("fs:write", path);
7107
+ await writeFile(expandHome(path), data);
7108
+ }
7109
+ },
7110
+ shell: {
7111
+ exec: async (command, args, opts) => {
7112
+ if (!allowsCommand(getGrants(), command))
7113
+ deny("shell", command);
7114
+ return deps.runner.spawn(expandHome(command), args, { cwd: opts?.cwd ?? homedir6(), timeout: opts?.timeoutMs });
7115
+ }
7116
+ },
7117
+ pty: {
7118
+ spawn: async (command, args, opts) => {
7119
+ if (!getGrants().pty)
7120
+ deny("pty", command);
7121
+ if (!deps.spawnPty)
7122
+ throw new Error("pty.spawn is not available in this Forge");
7123
+ return deps.spawnPty(command, args, opts);
7124
+ }
7125
+ },
7126
+ log: {
7127
+ info: (msg) => log.info(`${prefix} ${msg}`),
7128
+ warn: (msg) => log.warn(`${prefix} ${msg}`),
7129
+ error: (msg) => log.error(`${prefix} ${msg}`)
7130
+ }
7131
+ };
7132
+ }
7133
+ function toSessionInfo(s) {
7134
+ return {
7135
+ project: s.project,
7136
+ sessionDir: s.sessionDir ?? "",
7137
+ type: s.type,
7138
+ task: s.task,
7139
+ account: s.account,
7140
+ harness: s.harness,
7141
+ provider: s.provider,
7142
+ model: s.model,
7143
+ worktreePath: s.worktree
7144
+ };
7145
+ }
7146
+ function parseGitStatus(output) {
7147
+ const lines2 = output.split("\n").filter(Boolean);
7148
+ const status = { files: [] };
7149
+ for (const line of lines2) {
7150
+ if (line.startsWith("## ")) {
7151
+ const m = /^## ([^.\s]+)(?:\.\.\.\S+)?(?: \[(?:ahead (\d+))?(?:, )?(?:behind (\d+))?\])?/.exec(line);
7152
+ if (m) {
7153
+ status.branch = m[1];
7154
+ if (m[2])
7155
+ status.ahead = Number(m[2]);
7156
+ if (m[3])
7157
+ status.behind = Number(m[3]);
7158
+ }
7159
+ } else {
7160
+ status.files.push({ status: line.slice(0, 2).trim(), path: line.slice(3) });
7161
+ }
7162
+ }
7163
+ return status;
7164
+ }
7165
+ var init_module_context = __esm({
7166
+ "../core/dist/module-context.js"() {
7167
+ "use strict";
7168
+ init_dist();
7169
+ init_module_permissions();
7170
+ init_state_log();
7171
+ }
7172
+ });
7173
+
7174
+ // ../core/dist/module-host.js
7175
+ import { existsSync as existsSync13, readdirSync as readdirSync7, readFileSync as readFileSync11, statSync as statSync4, writeFileSync as writeFileSync5 } from "node:fs";
7176
+ import { basename as basename4, dirname as dirname7, join as join16, resolve as resolve6 } from "node:path";
7177
+ import { pathToFileURL } from "node:url";
7178
+ function disabled(id, c, reason, m) {
7179
+ const text = (v, fallback) => typeof v === "string" && v ? v : fallback;
7180
+ return { id, name: text(m?.name, id), version: text(m?.version, ""), displayName: text(m?.displayName, id), source: c.source, state: "disabled", reason };
7181
+ }
7182
+ function packages(root, source, packaged) {
7183
+ if (!existsSync13(root))
7184
+ return [];
7185
+ const out = [];
7186
+ const consider = (dir, name) => {
7187
+ const { file, hasForgeField } = manifestFileFor(dir);
7188
+ if (!hasForgeField && !/^@forge-dev\/mod-/.test(name))
7189
+ return;
7190
+ out.push({ dir, source, manifestFile: file, packaged: packaged && hasForgeField });
7191
+ };
7192
+ for (const entry of readdirSync7(root, { withFileTypes: true })) {
7193
+ if (!isDir(root, entry) || entry.name.startsWith("."))
7194
+ continue;
7195
+ if (entry.name.startsWith("@")) {
7196
+ for (const sub of readdirSync7(join16(root, entry.name), { withFileTypes: true })) {
7197
+ if (isDir(join16(root, entry.name), sub))
7198
+ consider(join16(root, entry.name, sub.name), `${entry.name}/${sub.name}`);
7199
+ }
7200
+ } else {
7201
+ consider(join16(root, entry.name), entry.name);
7202
+ }
7203
+ }
7204
+ return out;
7205
+ }
7206
+ function nearestPackage(dir) {
7207
+ for (let d = dir; ; d = dirname7(d)) {
7208
+ const path = join16(d, "package.json");
7209
+ if (existsSync13(path)) {
7210
+ try {
7211
+ return { path, type: JSON.parse(readFileSync11(path, "utf-8")).type };
7212
+ } catch {
7213
+ return { path };
7214
+ }
7215
+ }
7216
+ if (dirname7(d) === d)
7217
+ return null;
7218
+ }
7219
+ }
7220
+ function isDir(parent, entry) {
7221
+ if (entry.isDirectory())
7222
+ return true;
7223
+ if (!entry.isSymbolicLink())
7224
+ return false;
7225
+ try {
7226
+ return statSync4(join16(parent, entry.name)).isDirectory();
7227
+ } catch {
7228
+ return false;
7229
+ }
7230
+ }
7231
+ function checkServer(server, m) {
7232
+ if (typeof server !== "object" || server === null)
7233
+ return "server.js must default-export defineModule({...})";
7234
+ const s = server;
7235
+ for (const key of ["routes", "actions", "jobs", "events", "detectors"]) {
7236
+ if (s[key] !== void 0 && !Array.isArray(s[key]))
7237
+ return `server ${key} must be a list`;
7238
+ }
7239
+ const dupes = (kind, ids) => {
7240
+ const d = ids.find((id, i) => ids.indexOf(id) !== i);
7241
+ return d ? `duplicate ${kind} ${d}` : null;
7242
+ };
7243
+ const shellDeclared = (m.permissions?.shell?.length ?? 0) > 0;
7244
+ for (const action of s.actions ?? []) {
7245
+ if (isShellExecutor(action.run) && !shellDeclared)
7246
+ return `action ${action.id} uses shell but the manifest does not declare it`;
7247
+ if (action.effect === "external" && typeof action.confirm !== "function")
7248
+ return `action ${action.id} is external but has no confirm`;
7249
+ }
7250
+ for (const route of s.routes ?? []) {
7251
+ const first = route.path.split("/").filter(Boolean)[0] ?? "";
7252
+ if (RESERVED_SEGMENTS.has(first))
7253
+ return `route ${route.path} uses a reserved segment`;
7254
+ }
7255
+ return dupes("action", (s.actions ?? []).map((a) => a.id)) ?? dupes("route", (s.routes ?? []).map((r) => `${r.method} ${r.path}`)) ?? dupes("job", (s.jobs ?? []).map((j) => j.id));
7256
+ }
7257
+ var RESERVED_SEGMENTS, ModuleHost;
7258
+ var init_module_host = __esm({
7259
+ "../core/dist/module-host.js"() {
7260
+ "use strict";
7261
+ init_dist();
7262
+ init_module_manifest();
7263
+ init_module_permissions();
7264
+ init_module_context();
7265
+ init_modules();
7266
+ RESERVED_SEGMENTS = /* @__PURE__ */ new Set(["settings", "actions", "view.js", "status", "notifications", "reload"]);
7267
+ ModuleHost = class {
7268
+ opts;
7269
+ statuses = [];
7270
+ loaded = /* @__PURE__ */ new Map();
7271
+ constructor(opts) {
7272
+ this.opts = opts;
7273
+ }
7274
+ list() {
7275
+ return this.statuses;
7276
+ }
7277
+ get(id) {
7278
+ return this.loaded.get(id);
7279
+ }
7280
+ // scans, reloads and dev changes run one at a time: each one awaits imports midway
7281
+ queue = Promise.resolve();
7282
+ serial(fn) {
7283
+ const next = this.queue.then(fn, fn);
7284
+ this.queue = next.catch(() => {
7285
+ });
7286
+ return next;
7287
+ }
7288
+ scan() {
7289
+ return this.serial(() => this.scanNow());
7290
+ }
7291
+ async scanNow() {
7292
+ for (const id of [...this.loaded.keys()])
7293
+ this.unload(id);
7294
+ const statuses = [];
7295
+ const seen = /* @__PURE__ */ new Map();
7296
+ for (const candidate of this.candidates()) {
7297
+ const status = await this.loadCandidate(candidate, seen);
7298
+ if (status)
7299
+ statuses.push(status);
7300
+ }
7301
+ this.statuses = statuses;
7302
+ return statuses;
7303
+ }
7304
+ // only this module is unloaded and loaded again; the others keep running
7305
+ reload(id) {
7306
+ return this.serial(() => this.reloadNow(id));
7307
+ }
7308
+ async reloadNow(id) {
7309
+ const mod = this.loaded.get(id);
7310
+ if (!mod) {
7311
+ await this.scanNow();
7312
+ } else {
7313
+ this.unload(id);
7314
+ const seen = new Map([...this.loaded.values()].map((m) => [m.status.id, m.dir]));
7315
+ const status = await this.loadCandidate(mod.candidate, seen);
7316
+ this.statuses = this.statuses.flatMap((s) => s === mod.status ? status ? [status] : [] : [s]);
7317
+ }
7318
+ }
7319
+ addDev(path) {
7320
+ return this.serial(() => this.addDevNow(path));
7321
+ }
7322
+ async addDevNow(path) {
7323
+ const dirs = this.devDirs();
7324
+ const dir = resolve6(path);
7325
+ if (!dirs.includes(dir))
7326
+ writeFileSync5(this.opts.devFile, JSON.stringify([...dirs, dir], null, 2));
7327
+ await this.scanNow();
7328
+ return this.statuses.find((s) => this.loaded.get(s.id)?.dir === dir) ?? this.statuses.find((s) => s.state !== "enabled" && s.id === basename4(dir));
7329
+ }
7330
+ removeDev(path) {
7331
+ return this.serial(async () => {
7332
+ const dir = resolve6(path);
7333
+ writeFileSync5(this.opts.devFile, JSON.stringify(this.devDirs().filter((d) => d !== dir), null, 2));
7334
+ await this.scanNow();
7335
+ });
7336
+ }
7337
+ settings(id) {
7338
+ return this.loaded.get(id)?.settings ?? {};
7339
+ }
7340
+ saveSettings(id, values) {
7341
+ const mod = this.loaded.get(id);
7342
+ if (!mod)
7343
+ return { ok: false, errors: [{ path: "", message: "module not loaded" }] };
7344
+ const result2 = validateSettings(mod.manifest.settings?.schema ?? {}, values);
7345
+ if (!result2.ok)
7346
+ return result2;
7347
+ for (const key of Object.keys(mod.manifest.settings?.schema ?? {})) {
7348
+ if (result2.value[key] === void 0)
7349
+ this.opts.deps.db.deleteModuleSetting(id, key);
7350
+ else
7351
+ this.opts.deps.db.setModuleSetting(id, key, JSON.stringify(result2.value[key]));
7352
+ }
7353
+ mod.settings = result2.value;
7354
+ mod.grants = expandGrants(mod.manifest.permissions, result2.value);
7355
+ this.opts.hooks?.settingsChanged?.(mod);
7356
+ return { ok: true };
7357
+ }
7358
+ close() {
7359
+ for (const id of [...this.loaded.keys()])
7360
+ this.unload(id);
7361
+ }
7362
+ unload(id) {
7363
+ const mod = this.loaded.get(id);
7364
+ if (!mod)
7365
+ return;
7366
+ this.opts.hooks?.unloading?.(mod);
7367
+ mod.abort.abort();
7368
+ this.loaded.delete(id);
7369
+ }
7370
+ devDirs() {
7371
+ try {
7372
+ const raw = JSON.parse(readFileSync11(this.opts.devFile, "utf-8"));
7373
+ return Array.isArray(raw) ? raw.filter((d) => typeof d === "string") : [];
7374
+ } catch {
7375
+ return [];
7376
+ }
7377
+ }
7378
+ candidates() {
7379
+ const out = [];
7380
+ const folder = (dir, source) => out.push({ dir, source, manifestFile: join16(dir, "forge-module.json"), packaged: false });
7381
+ if (this.opts.bundledDir)
7382
+ for (const name of BUNDLED_MODULES)
7383
+ folder(join16(this.opts.bundledDir, name), "bundled");
7384
+ for (const dir of this.devDirs())
7385
+ folder(dir, "dev");
7386
+ if (existsSync13(this.opts.modulesDir)) {
7387
+ for (const entry of readdirSync7(this.opts.modulesDir, { withFileTypes: true })) {
7388
+ if (entry.isDirectory() && entry.name !== "node_modules" && !entry.name.startsWith("."))
7389
+ folder(join16(this.opts.modulesDir, entry.name), "installed");
7390
+ }
7391
+ out.push(...packages(join16(this.opts.modulesDir, "node_modules"), "node_modules", true));
7392
+ }
7393
+ if (this.opts.forgeNodeModules)
7394
+ out.push(...packages(this.opts.forgeNodeModules, "node_modules", false));
7395
+ return out;
7396
+ }
7397
+ async loadCandidate(c, seen) {
7398
+ const fallbackId = basename4(c.dir);
7399
+ if (!existsSync13(c.manifestFile)) {
7400
+ return c.packaged ? disabled(fallbackId, c, `no manifest at ${c.manifestFile}`) : void 0;
7401
+ }
7402
+ let raw;
7403
+ try {
7404
+ raw = JSON.parse(readFileSync11(c.manifestFile, "utf-8"));
7405
+ } catch (err) {
7406
+ return disabled(fallbackId, c, `forge-module.json is not valid JSON: ${err.message}`);
7407
+ }
7408
+ const check = checkManifest(raw, c.dir);
7409
+ const named = raw;
7410
+ const id = typeof named.id === "string" && named.id ? named.id : fallbackId;
7411
+ if (check.kind === "invalid")
7412
+ return disabled(id, c, check.reason, named);
7413
+ if (check.kind === "legacy") {
7414
+ return { id: fallbackId, name: check.manifest.name, version: check.manifest.version, displayName: check.manifest.displayName, source: c.source, state: "legacy", icon: check.manifest.icon, color: check.manifest.color };
7415
+ }
7416
+ const m = check.manifest;
7417
+ const firstFrom = seen.get(m.id);
7418
+ if (firstFrom)
7419
+ return disabled(m.id, c, `duplicate id, already loaded from ${firstFrom}`, m);
7420
+ seen.set(m.id, c.dir);
7421
+ if (!this.opts.localOnly && (m.server || m.view))
7422
+ return disabled(m.id, c, "modules run only in local mode", m);
7423
+ let server;
7424
+ if (m.server) {
7425
+ const file = resolve6(c.dir, m.server);
7426
+ const owner = file.endsWith(".js") ? nearestPackage(dirname7(file)) : null;
7427
+ if (owner?.type === "commonjs")
7428
+ return disabled(m.id, c, `${m.server} is an ES module but ${owner.path} says "type": "commonjs"; add "type": "module" to the module's package.json`, m);
7429
+ try {
7430
+ const imported = await import(`${pathToFileURL(file).href}?v=${statSync4(file).mtimeMs}`);
7431
+ server = imported.default;
7432
+ } catch (err) {
7433
+ return disabled(m.id, c, `server failed to load: ${err.message}`, m);
7434
+ }
7435
+ const problem = checkServer(server, m);
7436
+ if (problem)
7437
+ return disabled(m.id, c, problem, m);
7438
+ }
7439
+ const status = {
7440
+ id: m.id,
7441
+ name: m.name,
7442
+ version: m.version,
7443
+ displayName: m.displayName,
7444
+ source: c.source,
7445
+ state: "enabled",
7446
+ icon: m.icon,
7447
+ color: m.color,
7448
+ settingsSchema: m.settings?.schema,
7449
+ permissions: m.permissions,
7450
+ actions: server?.actions?.map((a) => ({ id: a.id, label: a.label, effect: a.effect }))
7451
+ };
7452
+ if (m.view) {
7453
+ const entry = resolve6(c.dir, m.view.entry);
7454
+ const mtime = existsSync13(entry) ? Math.floor(statSync4(entry).mtimeMs) : 0;
7455
+ status.view = { url: `/api/modules/${m.id}/view.js`, title: m.view.title ?? m.displayName, version: `${m.version}-${mtime}` };
7456
+ }
7457
+ const settings = this.readSettings(m);
7458
+ const abort = new AbortController();
7459
+ const mod = { status, dir: c.dir, manifest: m, server, abort, settings, candidate: c, grants: expandGrants(m.permissions, settings), ctx: void 0 };
7460
+ mod.ctx = createForgeContext(this.opts.deps, { id: m.id, version: m.version }, () => mod.settings, () => mod.grants, (permission, value) => {
7461
+ status.lastDenial = { permission, value, at: (/* @__PURE__ */ new Date()).toISOString() };
7462
+ });
7463
+ this.unload(m.id);
7464
+ this.loaded.set(m.id, mod);
7465
+ this.opts.hooks?.loaded?.(mod);
7466
+ return status;
7467
+ }
7468
+ // stored values are JSON per key; anything unreadable falls back to the schema defaults
7469
+ readSettings(m) {
7470
+ const schema = m.settings?.schema ?? {};
7471
+ const stored = {};
7472
+ for (const [key, value] of Object.entries(this.opts.deps.db.getModuleSettings(m.id))) {
7473
+ try {
7474
+ stored[key] = JSON.parse(value);
7475
+ } catch {
7476
+ }
7477
+ }
7478
+ const result2 = validateSettings(schema, stored);
7479
+ if (result2.ok)
7480
+ return result2.value;
7481
+ const defaults = validateSettings(schema, {});
7482
+ return defaults.ok ? defaults.value : {};
7483
+ }
7484
+ };
7485
+ }
7486
+ });
7487
+
7488
+ // ../core/dist/module-confirmations.js
7489
+ import { createHash as createHash3, randomBytes } from "node:crypto";
7490
+ function inputHash(input) {
7491
+ return createHash3("sha256").update(stable(input)).digest("hex");
7492
+ }
7493
+ function stable(value) {
7494
+ if (Array.isArray(value))
7495
+ return `[${value.map(stable).join(",")}]`;
7496
+ if (value && typeof value === "object") {
7497
+ return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stable(value[k])}`).join(",")}}`;
7498
+ }
7499
+ return JSON.stringify(value) ?? "null";
7500
+ }
7501
+ var TTL_MS2, Confirmations;
7502
+ var init_module_confirmations = __esm({
7503
+ "../core/dist/module-confirmations.js"() {
7504
+ "use strict";
7505
+ TTL_MS2 = 12e4;
7506
+ Confirmations = class {
7507
+ now;
7508
+ pending = /* @__PURE__ */ new Map();
7509
+ constructor(now = Date.now) {
7510
+ this.now = now;
7511
+ }
7512
+ issue(moduleId, actionId, hash, confirmation) {
7513
+ this.sweep();
7514
+ const token = randomBytes(24).toString("base64url");
7515
+ this.pending.set(token, { moduleId, actionId, hash, confirmation, expires: this.now() + TTL_MS2 });
7516
+ return token;
7517
+ }
7518
+ take(token, moduleId, actionId, hash) {
7519
+ const p = this.pending.get(token);
7520
+ if (!p)
7521
+ return null;
7522
+ this.pending.delete(token);
7523
+ if (p.expires < this.now() || p.moduleId !== moduleId || p.actionId !== actionId || p.hash !== hash)
7524
+ return null;
7525
+ return p.confirmation;
7526
+ }
7527
+ sweep() {
7528
+ const now = this.now();
7529
+ for (const [token, p] of this.pending)
7530
+ if (p.expires < now)
7531
+ this.pending.delete(token);
7532
+ }
7533
+ };
7534
+ }
7535
+ });
7536
+
7537
+ // ../core/dist/module-routes.js
7538
+ import { readFile as readFile2 } from "node:fs/promises";
7539
+ import { resolve as resolve7 } from "node:path";
7540
+ import { Hono as Hono5 } from "hono";
7541
+ function moduleRoutes(host, opts) {
7542
+ const { db } = opts;
7543
+ const confirmations = opts.confirmations ?? new Confirmations();
7544
+ const app = new Hono5();
7545
+ app.use("*", async (_c, next) => {
7546
+ await opts.ready;
7547
+ await next();
7548
+ });
7549
+ app.get("/", (c) => c.json(host.list()));
7550
+ app.post("/rescan", async (c) => c.json(await host.scan()));
7551
+ app.post("/dev", async (c) => {
7552
+ const { path } = await c.req.json();
7553
+ if (typeof path !== "string" || !path)
7554
+ return c.json({ code: "bad_request", message: "path is required" }, 400);
7555
+ return c.json({ status: await host.addDev(path), modules: host.list() });
7556
+ });
7557
+ app.delete("/dev", async (c) => {
7558
+ const { path } = await c.req.json();
7559
+ if (typeof path === "string")
7560
+ await host.removeDev(path);
7561
+ return c.json(host.list());
7562
+ });
7563
+ app.get("/notifications", (c) => c.json({
7564
+ items: db.listNotifications().map((n) => ({
7565
+ moduleId: n.moduleId,
7566
+ key: n.key,
7567
+ kind: n.kind,
7568
+ title: n.title,
7569
+ body: n.body,
7570
+ count: n.count,
7571
+ label: n.label,
7572
+ seen: n.seenAt != null,
7573
+ createdAt: n.createdAt
7574
+ }))
7575
+ }));
7576
+ app.post("/:id/notifications/seen", (c) => {
7577
+ db.markNotificationsSeen(c.req.param("id"));
7578
+ return c.json({ ok: true });
7579
+ });
7580
+ app.post("/:id/reload", async (c) => {
7581
+ await host.reload(c.req.param("id"));
7582
+ return c.json(host.list().find((s) => s.id === c.req.param("id")) ?? removed(c.req.param("id")));
7583
+ });
7584
+ app.get("/:id/status", (c) => {
7585
+ const status = host.list().find((s) => s.id === c.req.param("id"));
7586
+ return status ? c.json(status) : c.json(removed(c.req.param("id")), 404);
7587
+ });
7588
+ app.get("/:id/settings", (c) => {
7589
+ const id = c.req.param("id");
7590
+ return c.json(host.get(id) ? host.settings(id) : db.getModuleSettings(id));
7591
+ });
7592
+ app.put("/:id/settings", async (c) => {
7593
+ const id = c.req.param("id");
7594
+ const body2 = await c.req.json();
7595
+ if (!host.get(id)) {
7596
+ for (const [key, value] of Object.entries(body2))
7597
+ db.setModuleSetting(id, key, String(value));
7598
+ return c.json({ ok: true });
7599
+ }
7600
+ const result2 = host.saveSettings(id, body2);
7601
+ return result2.ok ? c.json({ ok: true }) : c.json({ errors: result2.errors }, 400);
7602
+ });
7603
+ app.get("/:id/view.js", async (c) => {
7604
+ const mod = host.get(c.req.param("id"));
7605
+ if (!mod?.manifest.view)
7606
+ return c.json(removed(c.req.param("id")), 404);
7607
+ try {
7608
+ const code = await readFile2(resolve7(mod.dir, mod.manifest.view.entry), "utf-8");
7609
+ return c.body(code, 200, { "Content-Type": "text/javascript; charset=utf-8", "Cache-Control": "no-cache" });
7610
+ } catch (err) {
7611
+ return c.json({ code: "not_found", message: `view bundle missing: ${err.message}` }, 404);
7612
+ }
7613
+ });
7614
+ app.post("/:id/actions/:action/prepare", async (c) => {
7615
+ const found = await findAction(c);
7616
+ if (found instanceof Response)
7617
+ return found;
7618
+ const { mod, action, input } = found;
7619
+ if (action.effect !== "external" || !action.confirm)
7620
+ return c.json({ code: "bad_request", message: `action ${action.id} needs no confirmation` }, 400);
7621
+ try {
7622
+ const confirmation = await action.confirm(input, mod.ctx);
7623
+ const token = confirmations.issue(mod.status.id, action.id, inputHash(input), confirmation);
7624
+ const { plan: _plan, ...shown } = confirmation;
7625
+ return c.json({ confirmation: shown, token });
7626
+ } catch (err) {
7627
+ return errorResponse(c, mod, err);
7628
+ }
7629
+ });
7630
+ app.post("/:id/actions/:action", async (c) => {
7631
+ const ready = await prepareRun(c);
7632
+ if (ready instanceof Response)
7633
+ return ready;
7634
+ try {
7635
+ return c.json({ result: await ready.run(() => {
7636
+ }) ?? null });
7637
+ } catch (err) {
7638
+ return errorResponse(c, ready.found.mod, err);
7639
+ }
7640
+ });
7641
+ app.post("/:id/actions/:action/stream", async (c) => {
7642
+ const ready = await prepareRun(c);
7643
+ if (ready instanceof Response)
7644
+ return ready;
7645
+ const { found } = ready;
7646
+ return new Response(new ReadableStream({
7647
+ async start(controller) {
7648
+ const encoder = new TextEncoder();
7649
+ const send = (event, data) => {
7650
+ try {
7651
+ controller.enqueue(encoder.encode(`event: ${event}
7652
+ data: ${JSON.stringify(data)}
7653
+
7654
+ `));
7655
+ } catch {
7656
+ }
7657
+ };
7658
+ send("start", { action: found.action.id });
7659
+ try {
7660
+ send("done", { result: await ready.run((chunk) => send("output", { chunk })) ?? null });
7661
+ } catch (err) {
7662
+ send("error", describe(err));
7663
+ }
7664
+ try {
7665
+ controller.close();
7666
+ } catch {
7667
+ }
7668
+ }
7669
+ }), { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" } });
7670
+ });
7671
+ app.all("/:id/*", async (c) => {
7672
+ const id = c.req.param("id");
7673
+ const mod = host.get(id);
7674
+ if (!mod)
7675
+ return c.json(removed(id), 404);
7676
+ const path = c.req.path.slice(c.req.path.indexOf(`/${id}/`) + id.length + 1);
7677
+ const match = matchRoute(mod.server?.routes ?? [], c.req.method, path);
7678
+ if (!match)
7679
+ return c.json({ code: "not_found", message: `${c.req.method} ${path} is not a route of ${id}` }, 404);
7680
+ try {
7681
+ const body2 = c.req.method === "GET" || c.req.method === "DELETE" ? void 0 : await readJson3(c);
7682
+ const result2 = await match.route.handler({ params: match.params, query: c.req.query(), body: body2 }, mod.ctx);
7683
+ return c.json(result2 ?? null);
7684
+ } catch (err) {
7685
+ return errorResponse(c, mod, err);
7686
+ }
7687
+ });
7688
+ async function findAction(c) {
7689
+ const id = c.req.param("id");
7690
+ const mod = host.get(id);
7691
+ if (!mod)
7692
+ return c.json(removed(id), 404);
7693
+ const action = mod.server?.actions?.find((a) => a.id === c.req.param("action"));
7694
+ if (!action)
7695
+ return c.json({ code: "not_found", message: `${id} has no action ${c.req.param("action")}` }, 404);
7696
+ const body2 = await readJson3(c) ?? {};
7697
+ let input = body2.input;
7698
+ if (action.input) {
7699
+ const checked = validateSettings(action.input, input);
7700
+ if (!checked.ok)
7701
+ return c.json({ code: "bad_request", message: "invalid input", errors: checked.errors }, 400);
7702
+ input = checked.value;
7703
+ }
7704
+ return { mod, action, input, token: typeof body2.token === "string" ? body2.token : void 0 };
7705
+ }
7706
+ async function prepareRun(c) {
7707
+ const found = await findAction(c);
7708
+ if (found instanceof Response)
7709
+ return found;
7710
+ let confirmation;
7711
+ if (found.action.effect === "external") {
7712
+ confirmation = found.token ? confirmations.take(found.token, found.mod.status.id, found.action.id, inputHash(found.input)) ?? void 0 : void 0;
7713
+ if (!confirmation)
7714
+ return c.json({ code: "confirmation_required", message: `${found.action.label} needs a confirmation first` }, 409);
7715
+ }
7716
+ const logId = db.logAction({
7717
+ projectId: null,
7718
+ moduleId: found.mod.status.id,
7719
+ actionId: found.action.id,
7720
+ command: `${found.action.effect} input:${inputHash(found.input).slice(0, 12)}`
7721
+ });
7722
+ const signal = c.req.raw.signal;
7723
+ return {
7724
+ found,
7725
+ run: async (output) => {
7726
+ try {
7727
+ const result2 = await run(found, confirmation, output, signal);
7728
+ db.completeAction(logId, 0);
7729
+ return result2;
7730
+ } catch (err) {
7731
+ db.completeAction(logId, 1);
7732
+ throw err;
7733
+ }
7734
+ }
7735
+ };
7736
+ }
7737
+ return app;
7738
+ }
7739
+ async function run(found, confirmation, output, requestSignal) {
7740
+ const { mod, action, input } = found;
7741
+ const signal = AbortSignal.any([mod.abort.signal, requestSignal]);
7742
+ if (isShellExecutor(action.run)) {
7743
+ const result2 = await mod.ctx.shell.exec(action.run.command, action.run.args);
7744
+ output(result2.output);
7745
+ return result2;
7746
+ }
7747
+ const ctx = Object.assign(Object.create(mod.ctx), { output, signal, confirmed: confirmation?.plan });
7748
+ return action.run(input, ctx);
7749
+ }
7750
+ async function readJson3(c) {
7751
+ const text = await c.req.text();
7752
+ if (!text)
7753
+ return void 0;
7754
+ try {
7755
+ return JSON.parse(text);
7756
+ } catch {
7757
+ return void 0;
7758
+ }
7759
+ }
7760
+ function removed(id) {
7761
+ return { code: "module_removed", message: `module ${id} is not loaded` };
7762
+ }
7763
+ function describe(err) {
7764
+ if (err instanceof PermissionError)
7765
+ return { code: "permission", message: err.message, permission: err.permission, value: err.value };
7766
+ const e = err;
7767
+ const message = typeof e?.message === "string" ? e.message : String(err);
7768
+ if (e?.name === "ModuleError" && typeof e.code === "string")
7769
+ return { code: e.code, message };
7770
+ return { code: "module_error", message };
7771
+ }
7772
+ function errorResponse(c, mod, err) {
7773
+ const body2 = describe(err);
7774
+ if (body2.code === "permission")
7775
+ return c.json(body2, 403);
7776
+ const status = STATUS_BY_CODE[body2.code];
7777
+ if (status)
7778
+ return c.json(body2, status);
7779
+ console.error(`[module ${mod.status.id}] ${err?.stack ?? body2.message}`);
7780
+ return c.json(body2, 500);
7781
+ }
7782
+ function matchRoute(routes, method, path) {
7783
+ const parts = path.split("/").filter(Boolean);
7784
+ for (const route of routes) {
7785
+ if (route.method !== method)
7786
+ continue;
7787
+ const pattern = route.path.split("/").filter(Boolean);
7788
+ if (pattern.length !== parts.length)
7789
+ continue;
7790
+ const params = {};
7791
+ if (pattern.every((seg, i) => {
7792
+ if (seg.startsWith(":")) {
7793
+ params[seg.slice(1)] = decodeURIComponent(parts[i]);
7794
+ return true;
7795
+ }
7796
+ return seg === parts[i];
7797
+ }))
7798
+ return { route, params };
7799
+ }
7800
+ return null;
7801
+ }
7802
+ var STATUS_BY_CODE;
7803
+ var init_module_routes = __esm({
7804
+ "../core/dist/module-routes.js"() {
7805
+ "use strict";
7806
+ init_dist();
7807
+ init_module_manifest();
7808
+ init_module_confirmations();
7809
+ STATUS_BY_CODE = {
7810
+ bad_request: 400,
7811
+ unauthorized: 401,
7812
+ not_found: 404,
7813
+ unreachable: 502,
7814
+ upstream: 502
7815
+ };
7816
+ }
7817
+ });
7818
+
7819
+ // ../core/dist/module-jobs.js
7820
+ function parseEvery(text) {
7821
+ const m = /^(\d+)(s|m|h)$/.exec(text.trim());
7822
+ if (!m)
7823
+ throw new Error("every must look like 30s, 2m or 1h");
7824
+ const ms = Number(m[1]) * UNITS[m[2]];
7825
+ if (ms < MIN_MS)
7826
+ throw new Error("every must be at least 30s");
7827
+ return ms;
7828
+ }
7829
+ var MIN_MS, UNITS, JobScheduler;
7830
+ var init_module_jobs = __esm({
7831
+ "../core/dist/module-jobs.js"() {
7832
+ "use strict";
7833
+ MIN_MS = 3e4;
7834
+ UNITS = { s: 1e3, m: 6e4, h: 36e5 };
7835
+ JobScheduler = class {
7836
+ opts;
7837
+ entries = /* @__PURE__ */ new Map();
7838
+ constructor(opts) {
7839
+ this.opts = opts;
7840
+ }
7841
+ start(moduleId, job, ctx) {
7842
+ let ms;
7843
+ try {
7844
+ ms = parseEvery(job.every);
7845
+ } catch (err) {
7846
+ this.opts.onResult(moduleId, job.id, err.message);
7847
+ return;
7848
+ }
7849
+ if (job.enabled && !job.enabled(ctx.settings))
7850
+ return;
7851
+ const entry = { lastError: null };
7852
+ const report = (error) => {
7853
+ if (error === entry.lastError)
7854
+ return;
7855
+ entry.lastError = error;
7856
+ this.opts.onResult(moduleId, job.id, error);
7857
+ };
7858
+ const tick = () => {
7859
+ if (entry.running) {
7860
+ if (Date.now() - entry.running.startedAt < ms)
7861
+ return;
7862
+ entry.running.abort.abort();
7863
+ entry.running = void 0;
7864
+ report(`timed out after ${ms / 1e3}s`);
7865
+ }
7866
+ const run2 = { abort: new AbortController(), startedAt: Date.now() };
7867
+ entry.running = run2;
7868
+ const jobCtx = Object.assign(Object.create(ctx), { signal: run2.abort.signal });
7869
+ Promise.resolve().then(() => job.run(jobCtx)).then(() => {
7870
+ if (entry.running === run2) {
7871
+ entry.running = void 0;
7872
+ report(null);
7873
+ }
7874
+ }, (err) => {
7875
+ if (entry.running === run2) {
7876
+ entry.running = void 0;
7877
+ report(err instanceof Error ? err.message : String(err));
7878
+ }
7879
+ });
7880
+ };
7881
+ entry.timer = setInterval(tick, ms);
7882
+ const list = this.entries.get(moduleId) ?? [];
7883
+ list.push(entry);
7884
+ this.entries.set(moduleId, list);
7885
+ tick();
7886
+ }
7887
+ stopModule(moduleId) {
7888
+ for (const entry of this.entries.get(moduleId) ?? []) {
7889
+ clearInterval(entry.timer);
7890
+ entry.running?.abort.abort();
7891
+ entry.running = void 0;
7892
+ }
7893
+ this.entries.delete(moduleId);
7894
+ }
7895
+ };
7896
+ }
7897
+ });
7898
+
7899
+ // ../core/dist/module-events.js
7900
+ var ModuleEvents;
7901
+ var init_module_events = __esm({
7902
+ "../core/dist/module-events.js"() {
7903
+ "use strict";
7904
+ ModuleEvents = class {
7905
+ opts;
7906
+ subs = [];
7907
+ timeoutMs;
7908
+ constructor(opts) {
7909
+ this.opts = opts;
7910
+ this.timeoutMs = opts.timeoutMs ?? 1e4;
7911
+ }
7912
+ subscribe(moduleId, sub, ctx) {
7913
+ this.subs.push({ moduleId, sub, ctx });
7914
+ }
7915
+ unsubscribeModule(moduleId) {
7916
+ this.subs = this.subs.filter((s) => s.moduleId !== moduleId);
7917
+ }
7918
+ emit(name, payload) {
7919
+ this.dispatch(this.subs.filter((s) => s.sub.event === name), name, payload);
7920
+ }
7921
+ emitTo(moduleId, name, payload) {
7922
+ this.dispatch(this.subs.filter((s) => s.sub.event === name && s.moduleId === moduleId), name, payload);
7923
+ }
7924
+ dispatch(targets, name, payload) {
7925
+ if (targets.length === 0)
7926
+ return;
7927
+ setTimeout(async () => {
7928
+ for (const { moduleId, sub, ctx } of targets) {
7929
+ let timer;
7930
+ try {
7931
+ await Promise.race([
7932
+ Promise.resolve().then(() => sub.handler(payload, ctx)),
7933
+ new Promise((_, reject) => {
7934
+ timer = setTimeout(() => reject(new Error(`timed out after ${this.timeoutMs / 1e3}s`)), this.timeoutMs);
7935
+ })
7936
+ ]);
7937
+ } catch (err) {
7938
+ this.opts.onError(moduleId, `${name}: ${err instanceof Error ? err.message : String(err)}`);
7939
+ } finally {
7940
+ clearTimeout(timer);
7941
+ }
7942
+ }
7943
+ }, 0);
7944
+ }
7945
+ };
7946
+ }
7947
+ });
7948
+
7949
+ // ../core/dist/server.js
7950
+ import { Hono as Hono6 } from "hono";
7951
+ import { cors } from "hono/cors";
7952
+ import { join as join17, basename as basename5, resolve as resolve8 } from "node:path";
7953
+ import { readdirSync as readdirSync8, existsSync as existsSync14 } from "node:fs";
7954
+ function createForgeServer(options) {
7955
+ const { dataDir, db: externalDb, authToken, localOnly = true } = options;
7956
+ const dbPath = join17(dataDir, "forge.db");
7957
+ const modulesDir = join17(dataDir, "modules");
7958
+ const db = externalDb ?? new ForgeDB(dbPath);
7959
+ const loader = new ModuleLoader(modulesDir, options.bundledModulesDir);
7960
+ const runner = new ActionRunner();
7961
+ loader.discover();
7962
+ const app = new Hono6();
7963
+ app.use("*", localOnly ? localOriginGuard() : cors());
7964
+ if (authToken) {
7965
+ app.use("/api/*", bearerAuth(authToken));
7966
+ }
7967
+ const cwReader = new CWReader(options.cwDir);
7968
+ const loginManager = new LoginManager(resolveCwBin(cwReader.cwHome));
7969
+ app.route("/api/cw", cwRoutes(cwReader, { loginManager, localOnly, events: { emit: (name, payload) => moduleEvents.emit(name, payload) } }));
7970
+ app.route("/api/skills", skillRoutes(cwReader, { backupDir: join17(dataDir, "skill-backups") }));
7971
+ const { remote, shadow, warning } = remoteClassifierFromEnv();
7972
+ if (warning)
7973
+ console.warn(`[state] ${warning}`);
7974
+ const logPath = process.env.FORGE_STATE_LOG;
7975
+ if (logPath && !remote)
7976
+ console.warn("[state] FORGE_STATE_LOG only records remote classifier calls; set FORGE_STATE_CLASSIFIER=jev");
7977
+ const onRemote = logPath && remote ? createStateLog(logPath, (err) => console.warn(`[state] could not write ${logPath}: ${err.message}`)) : void 0;
7978
+ let lastStateError = "";
7979
+ const states = new StateTracker({
7980
+ remote,
7981
+ shadow,
7982
+ onRemote,
7983
+ onError: (err) => {
7984
+ if (err.message !== lastStateError)
7985
+ console.warn(`[state] ${remote?.name ?? "remote"} classifier failed, using local rules: ${err.message}`);
7986
+ lastStateError = err.message;
7987
+ }
7988
+ });
7989
+ const ptyManager = new PTYManager(states);
7990
+ const generalSessions = new GeneralSessions(join17(dataDir, "general-sessions.json"));
7991
+ const terminalWss = createTerminalWss(ptyManager, cwReader, { localOnly, general: generalSessions });
7992
+ app.route("/api/liveframe", liveframeRoutes());
7993
+ const kioku = new Kioku({ projects: () => cwReader.getProjects() });
7994
+ app.route("/api/kioku", kiokuRoutes(kioku, {
7995
+ type: (project, sessionDir, text) => ptyManager.typeLine(project, sessionDir, text),
7996
+ // kioku's plugin, and so its skill, exists only for Claude Code
7997
+ canRemember: (project, sessionDir) => cwReader.getSession(project, sessionDir)?.harness === "claude"
7998
+ }));
7999
+ const jobs = new JobScheduler({
8000
+ onResult: (id, jobId, error) => {
8001
+ const status = moduleHost.get(id)?.status;
8002
+ if (status)
8003
+ status.lastJobError = error ? `${jobId}: ${error}` : void 0;
8004
+ if (error)
8005
+ console.warn(`[module ${id}] job ${jobId}: ${error}`);
8006
+ }
8007
+ });
8008
+ const moduleEvents = new ModuleEvents({
8009
+ onError: (id, message) => {
8010
+ const status = moduleHost.get(id)?.status;
8011
+ if (status)
8012
+ status.lastEventError = message;
8013
+ console.warn(`[module ${id}] ${message}`);
8014
+ }
8015
+ });
8016
+ const startModule = (mod) => {
8017
+ for (const job of mod.server?.jobs ?? [])
8018
+ jobs.start(mod.status.id, job, mod.ctx);
8019
+ };
8020
+ const moduleHost = new ModuleHost({
8021
+ modulesDir,
8022
+ bundledDir: options.bundledModulesDir,
8023
+ forgeNodeModules: options.forgeNodeModules,
8024
+ devFile: join17(dataDir, "dev-modules.json"),
8025
+ localOnly,
8026
+ deps: { db, reader: cwReader, runner },
8027
+ hooks: {
8028
+ loaded: (mod) => {
8029
+ for (const sub of mod.server?.events ?? [])
8030
+ moduleEvents.subscribe(mod.status.id, sub, mod.ctx);
8031
+ startModule(mod);
8032
+ },
8033
+ unloading: (mod) => {
8034
+ jobs.stopModule(mod.status.id);
8035
+ moduleEvents.unsubscribeModule(mod.status.id);
8036
+ },
8037
+ settingsChanged: (mod) => {
8038
+ jobs.stopModule(mod.status.id);
8039
+ startModule(mod);
8040
+ moduleEvents.emitTo(mod.status.id, "module.settings.changed", { moduleId: mod.status.id });
8041
+ }
8042
+ }
8043
+ });
8044
+ const sessionEvent = (s) => ({
8045
+ project: s.project,
8046
+ sessionDir: s.sessionDir ?? "",
8047
+ type: s.type,
8048
+ account: s.account,
8049
+ harness: s.harness,
8050
+ provider: s.provider,
8051
+ model: s.model
8052
+ });
8053
+ ptyManager.onLifecycle = (event, session) => moduleEvents.emit(event === "started" ? "session.started" : "session.ended", sessionEvent(session));
8054
+ const modulesReady = moduleHost.scan().catch((err) => console.error(`[modules] scan failed: ${err.message}`));
8055
+ app.route("/api/modules", moduleRoutes(moduleHost, { db, ready: modulesReady }));
8056
+ app.get("/api/cw/session-states", (c) => c.json({ classifier: states.remoteName ?? "local", shadow: states.isShadow, states: states.snapshot() }));
8057
+ app.post("/api/cw/terminal/kill", async (c) => {
8058
+ const { project, sessionDir } = await c.req.json();
8059
+ const sessionId = `${project}::${sessionDir}`;
8060
+ ptyManager.kill(sessionId);
8061
+ generalSessions.forget(sessionId);
8062
+ return c.json({ ok: true });
8063
+ });
8064
+ async function resolveAction(c) {
8065
+ const moduleName = c.req.param("module");
8066
+ const actionId = c.req.param("action");
8067
+ const { projectId, cwProject, params } = await c.req.json();
8068
+ const action = loader.getAction(moduleName, actionId);
8069
+ if (!action) {
8070
+ return c.json({ error: "Action not found" }, 404);
8071
+ }
8072
+ const checked = validateParams(action, params);
8073
+ if ("error" in checked) {
8074
+ return c.json({ error: checked.error }, 400);
8075
+ }
8076
+ let cwd;
8077
+ if (cwProject !== void 0) {
8078
+ const projects = cwReader.getProjects();
8079
+ const path = Object.hasOwn(projects, cwProject) ? projects[cwProject]?.path : void 0;
8080
+ if (!path)
8081
+ return c.json({ error: `Unknown CW project: ${cwProject}` }, 400);
8082
+ cwd = path;
8083
+ } else {
8084
+ cwd = (projectId ? db.getProject(projectId) : void 0)?.path ?? process.cwd();
8085
+ }
8086
+ const logId = db.logAction({
8087
+ projectId: projectId ?? null,
8088
+ moduleId: moduleName,
8089
+ actionId,
8090
+ command: action.command
8091
+ });
8092
+ return { action, cwd, logId, env: checked.env };
8093
+ }
8094
+ app.get("/api/health", (c) => {
8095
+ return c.json({
8096
+ status: "ok",
8097
+ version: options.version ?? null,
8098
+ modules: loader.getLoadedCount()
8099
+ });
8100
+ });
8101
+ app.get("/api/projects", (c) => {
8102
+ return c.json(db.listProjects());
8103
+ });
8104
+ app.post("/api/projects", async (c) => {
8105
+ const { name, path } = await c.req.json();
8106
+ const id = db.addProject({ name, path });
8107
+ const project = db.getProject(id);
8108
+ return c.json(project, 201);
8109
+ });
8110
+ app.delete("/api/projects/:id", (c) => {
8111
+ db.removeProject(c.req.param("id"));
8112
+ return c.json({ ok: true });
8113
+ });
8114
+ app.get("/api/modules/available", (c) => {
8115
+ const manifests = loader.discover();
8116
+ return c.json(manifests);
8117
+ });
8118
+ app.post("/api/actions/:module/:action", async (c) => {
8119
+ const resolved = await resolveAction(c);
8120
+ if (resolved instanceof Response)
8121
+ return resolved;
8122
+ const { action, cwd, logId, env } = resolved;
8123
+ const result2 = await runner.exec(action.command, { cwd, env });
8124
+ db.completeAction(logId, result2.exitCode);
8125
+ return c.json({
8126
+ logId,
8127
+ exitCode: result2.exitCode,
8128
+ output: result2.output,
8129
+ timedOut: result2.timedOut
8130
+ });
8131
+ });
8132
+ app.post("/api/actions/:module/:action/stream", async (c) => {
8133
+ const resolved = await resolveAction(c);
8134
+ if (resolved instanceof Response)
8135
+ return resolved;
8136
+ const { action, cwd, logId, env } = resolved;
8137
+ return new Response(new ReadableStream({
8138
+ async start(controller) {
8139
+ const encoder = new TextEncoder();
8140
+ const send = (event, data) => {
8141
+ controller.enqueue(encoder.encode(`event: ${event}
8142
+ data: ${JSON.stringify(data)}
8143
+
8144
+ `));
8145
+ };
8146
+ send("start", { logId, command: action.command });
8147
+ const result2 = await runner.exec(action.command, {
8148
+ cwd,
8149
+ env,
8150
+ onData: (chunk) => send("output", { chunk })
8151
+ });
8152
+ db.completeAction(logId, result2.exitCode);
8153
+ send("done", { exitCode: result2.exitCode, timedOut: result2.timedOut });
8154
+ controller.close();
8155
+ }
8156
+ }), {
8157
+ headers: {
8158
+ "Content-Type": "text/event-stream",
8159
+ "Cache-Control": "no-cache",
8160
+ Connection: "keep-alive"
8161
+ }
8162
+ });
8163
+ });
8164
+ app.get("/api/action-logs", (c) => {
8165
+ const moduleId = c.req.query("moduleId");
8166
+ const limitStr = c.req.query("limit");
8167
+ const limit = limitStr ? parseInt(limitStr, 10) : void 0;
8168
+ return c.json(db.listActionLogs({ moduleId, limit }));
8169
+ });
8170
+ app.get("/api/registry/search", async (c) => {
8171
+ const q = c.req.query("q") ?? "forge-dev";
8172
+ try {
8173
+ const npmRes = await globalThis.fetch(`https://registry.npmjs.org/-/v1/search?text=${encodeURIComponent(q)}+keywords:forge-module&size=20`);
8174
+ const data = await npmRes.json();
8175
+ const results = (data.objects ?? []).map((o) => ({
8176
+ name: o.package.name,
8177
+ version: o.package.version,
8178
+ description: o.package.description
8179
+ }));
8180
+ return c.json({ results });
8181
+ } catch {
8182
+ return c.json({ results: [] });
8183
+ }
8184
+ });
8185
+ app.get("/api/filesystem/browse", (c) => {
8186
+ const home = process.env.HOME ?? "/tmp";
8187
+ const dir = resolve8(c.req.query("path") ?? process.cwd());
8188
+ if (!dir.startsWith(home)) {
8189
+ return c.json({ error: "Access denied: path must be within home directory" }, 403);
8190
+ }
8191
+ if (!existsSync14(dir)) {
8192
+ return c.json({ error: "Directory not found" }, 404);
8193
+ }
8194
+ try {
8195
+ const entries = readdirSync8(dir, { withFileTypes: true });
8196
+ const dirs = entries.filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => ({
8197
+ name: e.name,
8198
+ path: join17(dir, e.name),
8199
+ hasPackageJson: existsSync14(join17(dir, e.name, "package.json")),
8200
+ hasGit: existsSync14(join17(dir, e.name, ".git"))
8201
+ })).sort((a, b) => a.name.localeCompare(b.name));
4782
8202
  return c.json({
4783
8203
  current: dir,
4784
- name: basename3(dir),
4785
- parent: join14(dir, ".."),
8204
+ name: basename5(dir),
8205
+ parent: join17(dir, ".."),
4786
8206
  directories: dirs
4787
8207
  });
4788
8208
  } catch {
@@ -4796,7 +8216,9 @@ data: ${JSON.stringify(data)}
4796
8216
  app,
4797
8217
  fetch: fetch2,
4798
8218
  attachTerminalWs: (server) => terminalWss.attachToServer(server),
8219
+ modulesReady,
4799
8220
  close: () => {
8221
+ moduleHost.close();
4800
8222
  ptyManager.dispose();
4801
8223
  states.dispose();
4802
8224
  loginManager.dispose();
@@ -4825,6 +8247,10 @@ var init_server = __esm({
4825
8247
  init_general_sessions();
4826
8248
  init_liveframe_routes();
4827
8249
  init_kioku_routes();
8250
+ init_module_host();
8251
+ init_module_routes();
8252
+ init_module_jobs();
8253
+ init_module_events();
4828
8254
  init_kioku();
4829
8255
  }
4830
8256
  });
@@ -4836,6 +8262,9 @@ __export(db_postgres_exports, {
4836
8262
  });
4837
8263
  import postgres from "postgres";
4838
8264
  import { randomUUID as randomUUID2 } from "node:crypto";
8265
+ function teamModeOnly() {
8266
+ throw new Error("not available in team mode");
8267
+ }
4839
8268
  var PostgresDB;
4840
8269
  var init_db_postgres = __esm({
4841
8270
  "../core/dist/db-postgres.js"() {
@@ -4930,6 +8359,33 @@ var init_db_postgres = __esm({
4930
8359
  setModuleSetting(moduleId, key, value) {
4931
8360
  this.sql`INSERT INTO module_settings (module_id, key, value) VALUES (${moduleId}, ${key}, ${value}) ON CONFLICT (module_id, key) DO UPDATE SET value = EXCLUDED.value`.execute();
4932
8361
  }
8362
+ deleteModuleSetting(moduleId, key) {
8363
+ this.sql`DELETE FROM module_settings WHERE module_id = ${moduleId} AND key = ${key}`.execute();
8364
+ }
8365
+ kvGet(_moduleId, _key) {
8366
+ return teamModeOnly();
8367
+ }
8368
+ kvSet(_moduleId, _key, _json) {
8369
+ teamModeOnly();
8370
+ }
8371
+ kvDelete(_moduleId, _key) {
8372
+ teamModeOnly();
8373
+ }
8374
+ kvList(_moduleId, _prefix) {
8375
+ return teamModeOnly();
8376
+ }
8377
+ upsertNotification(_row) {
8378
+ return teamModeOnly();
8379
+ }
8380
+ deleteNotification(_moduleId, _key) {
8381
+ teamModeOnly();
8382
+ }
8383
+ listNotifications() {
8384
+ return [];
8385
+ }
8386
+ markNotificationsSeen(_moduleId) {
8387
+ teamModeOnly();
8388
+ }
4933
8389
  listActionLogs(_opts) {
4934
8390
  throw new Error("PostgresDB.listActionLogs() not implemented \u2014 team mode is not yet supported");
4935
8391
  }
@@ -4948,8 +8404,8 @@ async function createDatabase(opts) {
4948
8404
  await db.migrate();
4949
8405
  return db;
4950
8406
  }
4951
- const { join: join17 } = await import("node:path");
4952
- return new ForgeDB(join17(opts.dataDir, "forge.db"));
8407
+ const { join: join21 } = await import("node:path");
8408
+ return new ForgeDB(join21(opts.dataDir, "forge.db"));
4953
8409
  }
4954
8410
  var init_db_factory = __esm({
4955
8411
  "../core/dist/db-factory.js"() {
@@ -4959,22 +8415,22 @@ var init_db_factory = __esm({
4959
8415
  });
4960
8416
 
4961
8417
  // ../core/dist/init.js
4962
- import { existsSync as existsSync14, mkdirSync as mkdirSync5, writeFileSync as writeFileSync5 } from "node:fs";
4963
- import { join as join15 } from "node:path";
4964
- import { homedir as homedir6 } from "node:os";
8418
+ import { existsSync as existsSync15, mkdirSync as mkdirSync5, writeFileSync as writeFileSync6 } from "node:fs";
8419
+ import { join as join18 } from "node:path";
8420
+ import { homedir as homedir7 } from "node:os";
4965
8421
  function getForgeDir() {
4966
- return join15(homedir6(), ".forge");
8422
+ return join18(homedir7(), ".forge");
4967
8423
  }
4968
8424
  function ensureForgeDir() {
4969
8425
  const forgeDir = getForgeDir();
4970
- if (existsSync14(forgeDir)) {
8426
+ if (existsSync15(forgeDir)) {
4971
8427
  return { forgeDir, created: false };
4972
8428
  }
4973
8429
  mkdirSync5(forgeDir, { recursive: true });
4974
8430
  for (const d of FORGE_SUBDIRS) {
4975
- mkdirSync5(join15(forgeDir, d), { recursive: true });
8431
+ mkdirSync5(join18(forgeDir, d), { recursive: true });
4976
8432
  }
4977
- writeFileSync5(join15(forgeDir, "config.json"), JSON.stringify({
8433
+ writeFileSync6(join18(forgeDir, "config.json"), JSON.stringify({
4978
8434
  port: 3e3,
4979
8435
  theme: "dark",
4980
8436
  openBrowser: true,
@@ -4994,14 +8450,14 @@ var init_init = __esm({
4994
8450
  function waitForListening(server) {
4995
8451
  if (server.listening)
4996
8452
  return Promise.resolve();
4997
- return new Promise((resolve5, reject) => {
8453
+ return new Promise((resolve10, reject) => {
4998
8454
  const onError = (err) => {
4999
8455
  server.off("listening", onListening);
5000
8456
  reject(err);
5001
8457
  };
5002
8458
  const onListening = () => {
5003
8459
  server.off("error", onError);
5004
- resolve5();
8460
+ resolve10();
5005
8461
  };
5006
8462
  server.once("error", onError);
5007
8463
  server.once("listening", onListening);
@@ -5036,6 +8492,68 @@ var init_port_in_use = __esm({
5036
8492
  }
5037
8493
  });
5038
8494
 
8495
+ // ../core/dist/module-install.js
8496
+ import { existsSync as existsSync16, mkdtempSync, readFileSync as readFileSync12, rmSync as rmSync3 } from "node:fs";
8497
+ import { tmpdir } from "node:os";
8498
+ import { isAbsolute as isAbsolute2, join as join19, resolve as resolve9 } from "node:path";
8499
+ async function previewManifest(spec, opts) {
8500
+ if (isPathSpec(spec, opts.cwd))
8501
+ return readFolder(expand(spec, opts.cwd));
8502
+ const tmp = mkdtempSync(join19(tmpdir(), "forge-module-pack-"));
8503
+ try {
8504
+ const packed = await opts.run("npm", ["pack", spec, "--pack-destination", tmp, "--ignore-scripts", "--json"], opts.cwd);
8505
+ if (packed.code !== 0)
8506
+ throw new Error(`npm pack ${spec} failed: ${(packed.stderr || packed.stdout).trim()}`);
8507
+ const filename = JSON.parse(packed.stdout)[0]?.filename;
8508
+ if (!filename)
8509
+ throw new Error(`npm pack ${spec} produced no tarball`);
8510
+ const untar = await opts.run("tar", ["-xzf", join19(tmp, filename), "-C", tmp], opts.cwd);
8511
+ if (untar.code !== 0)
8512
+ throw new Error(`could not unpack ${filename}: ${untar.stderr.trim()}`);
8513
+ return readFolder(join19(tmp, "package"));
8514
+ } finally {
8515
+ rmSync3(tmp, { recursive: true, force: true });
8516
+ }
8517
+ }
8518
+ function readFolder(dir) {
8519
+ const manifestFile = manifestFileFor(dir).file;
8520
+ if (!existsSync16(manifestFile))
8521
+ throw new Error(`${dir} has no forge-module.json`);
8522
+ const raw = JSON.parse(readFileSync12(manifestFile, "utf-8"));
8523
+ const check = checkManifest(raw, dir);
8524
+ if (check.kind === "invalid")
8525
+ throw new Error(`invalid manifest: ${check.reason}`);
8526
+ return check;
8527
+ }
8528
+ function describePermissions(manifest) {
8529
+ const p = "permissions" in manifest ? manifest.permissions ?? {} : {};
8530
+ const lines2 = [];
8531
+ for (const key of ["network", "fs:read", "fs:write", "shell"]) {
8532
+ for (const value of p[key] ?? [])
8533
+ lines2.push(` ${key.padEnd(9)} ${value}`);
8534
+ }
8535
+ if (p.pty)
8536
+ lines2.push(` ${"pty".padEnd(9)} yes`);
8537
+ const legacy = "actions" in manifest && (manifest.actions ?? []).some((a) => "command" in a);
8538
+ if (legacy)
8539
+ lines2.push(" shell runs the shell commands in its manifest");
8540
+ return [lines2.length ? "It asks for:" : "It asks for no permissions.", ...lines2, "", TRUST_NOTE].join("\n");
8541
+ }
8542
+ function installArgs(spec, prefix) {
8543
+ return ["install", "--ignore-scripts", "--prefix", prefix, spec];
8544
+ }
8545
+ var TRUST_NOTE, isPathSpec, expand;
8546
+ var init_module_install = __esm({
8547
+ "../core/dist/module-install.js"() {
8548
+ "use strict";
8549
+ init_module_manifest();
8550
+ init_state_log();
8551
+ TRUST_NOTE = "Modules run inside Forge with your access. Forge checks every call against these permissions, but it is not a sandbox: install only modules you trust.";
8552
+ isPathSpec = (spec, cwd) => spec.startsWith(".") || spec.startsWith("~") || isAbsolute2(spec) || existsSync16(resolve9(cwd, spec)) && !spec.startsWith("@");
8553
+ expand = (spec, cwd) => resolve9(cwd, expandHome(spec));
8554
+ }
8555
+ });
8556
+
5039
8557
  // ../core/dist/index.js
5040
8558
  var dist_exports = {};
5041
8559
  __export(dist_exports, {
@@ -5053,18 +8571,23 @@ __export(dist_exports, {
5053
8571
  ModuleLoader: () => ModuleLoader,
5054
8572
  PROVIDER_NAME_RE: () => PROVIDER_NAME_RE,
5055
8573
  PTYManager: () => PTYManager,
8574
+ TRUST_NOTE: () => TRUST_NOTE,
5056
8575
  bearerAuth: () => bearerAuth,
5057
8576
  createDatabase: () => createDatabase,
5058
8577
  createForgeServer: () => createForgeServer,
8578
+ createRunner: () => createRunner,
5059
8579
  createTerminalWss: () => createTerminalWss,
5060
8580
  cwRoutes: () => cwRoutes,
8581
+ describePermissions: () => describePermissions,
5061
8582
  ensureCw: () => ensureCw,
5062
8583
  ensureForgeDir: () => ensureForgeDir,
5063
8584
  getForgeDir: () => getForgeDir,
8585
+ installArgs: () => installArgs,
5064
8586
  kiokuRoutes: () => kiokuRoutes,
5065
8587
  liveframeRoutes: () => liveframeRoutes,
5066
8588
  pathWithCw: () => pathWithCw,
5067
8589
  portInUseMessage: () => portInUseMessage,
8590
+ previewManifest: () => previewManifest,
5068
8591
  probePort: () => probePort,
5069
8592
  quietSqliteWarning: () => quietSqliteWarning,
5070
8593
  rememberPrompt: () => rememberPrompt,
@@ -5075,7 +8598,7 @@ __export(dist_exports, {
5075
8598
  validateParams: () => validateParams,
5076
8599
  waitForListening: () => waitForListening
5077
8600
  });
5078
- var init_dist = __esm({
8601
+ var init_dist2 = __esm({
5079
8602
  "../core/dist/index.js"() {
5080
8603
  "use strict";
5081
8604
  init_server();
@@ -5100,13 +8623,15 @@ var init_dist = __esm({
5100
8623
  init_kioku_routes();
5101
8624
  init_kioku();
5102
8625
  init_port_in_use();
8626
+ init_module_install();
8627
+ init_task_review();
5103
8628
  }
5104
8629
  });
5105
8630
 
5106
8631
  // src/index.ts
5107
- import { existsSync as existsSync15, readFileSync as readFileSync10 } from "node:fs";
5108
- import { homedir as homedir7 } from "node:os";
5109
- import { join as join16 } from "node:path";
8632
+ import { existsSync as existsSync17, readFileSync as readFileSync13 } from "node:fs";
8633
+ import { homedir as homedir8 } from "node:os";
8634
+ import { join as join20 } from "node:path";
5110
8635
  function parseArgs(argv) {
5111
8636
  const out = { open: true };
5112
8637
  for (let i = 0; i < argv.length; i++) {
@@ -5117,21 +8642,21 @@ function parseArgs(argv) {
5117
8642
  }
5118
8643
  return out;
5119
8644
  }
5120
- var packageRoot = join16(import.meta.dirname, "..");
5121
- var isCheckout = existsSync15(join16(packageRoot, "src"));
5122
- var consoleDist = isCheckout ? join16(packageRoot, "../console/dist") : join16(packageRoot, "console");
5123
- var forgeVersion = JSON.parse(readFileSync10(join16(packageRoot, "package.json"), "utf-8")).version;
5124
- var bundledModulesDir = isCheckout ? join16(packageRoot, "../../modules") : join16(packageRoot, "modules");
8645
+ var packageRoot = join20(import.meta.dirname, "..");
8646
+ var isCheckout = existsSync17(join20(packageRoot, "src"));
8647
+ var consoleDist = isCheckout ? join20(packageRoot, "../console/dist") : join20(packageRoot, "console");
8648
+ var forgeVersion = JSON.parse(readFileSync13(join20(packageRoot, "package.json"), "utf-8")).version;
8649
+ var bundledModulesDir = isCheckout ? join20(packageRoot, "../../modules") : join20(packageRoot, "modules");
5125
8650
  async function main() {
5126
- const { ensureForgeDir: ensureForgeDir2, createForgeServer: createForgeServer2, createDatabase: createDatabase2, resolveListenOptions: resolveListenOptions2, ensureCw: ensureCw2, pathWithCw: pathWithCw2, quietSqliteWarning: quietSqliteWarning2, waitForListening: waitForListening2, probePort: probePort2, portInUseMessage: portInUseMessage2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
8651
+ const { ensureForgeDir: ensureForgeDir2, createForgeServer: createForgeServer2, createDatabase: createDatabase2, resolveListenOptions: resolveListenOptions2, ensureCw: ensureCw2, pathWithCw: pathWithCw2, quietSqliteWarning: quietSqliteWarning2, waitForListening: waitForListening2, probePort: probePort2, portInUseMessage: portInUseMessage2 } = await Promise.resolve().then(() => (init_dist2(), dist_exports));
5127
8652
  quietSqliteWarning2();
5128
8653
  const args = parseArgs(process.argv.slice(2));
5129
8654
  const { forgeDir, created } = ensureForgeDir2();
5130
8655
  if (created) {
5131
8656
  console.log("First run \u2014 initialized Forge.");
5132
8657
  }
5133
- const cwHome = join16(process.env.HOME ?? homedir7(), ".cw");
5134
- const cw = isCheckout ? { action: "skipped", message: "a checkout does not install CW" } : await ensureCw2({ cwHome, bundleDir: join16(packageRoot, "cw") });
8658
+ const cwHome = join20(process.env.HOME ?? homedir8(), ".cw");
8659
+ const cw = isCheckout ? { action: "skipped", message: "a checkout does not install CW" } : await ensureCw2({ cwHome, bundleDir: join20(packageRoot, "cw") });
5135
8660
  if (cw.action === "installed") console.log(` Installed CW ${cw.version} in ${cwHome}`);
5136
8661
  else if (cw.action === "updated") console.log(` Updated ${cw.message}`);
5137
8662
  else if (cw.action === "failed") console.log(` Could not install CW: ${cw.message}`);
@@ -5156,9 +8681,9 @@ async function main() {
5156
8681
  version: forgeVersion
5157
8682
  });
5158
8683
  const { serveStatic } = await import("@hono/node-server/serve-static");
5159
- if (existsSync15(join16(consoleDist, "index.html"))) {
8684
+ if (existsSync17(join20(consoleDist, "index.html"))) {
5160
8685
  server.app.use("/*", serveStatic({ root: consoleDist }));
5161
- const indexHtml = readFileSync10(join16(consoleDist, "index.html"), "utf-8");
8686
+ const indexHtml = readFileSync13(join20(consoleDist, "index.html"), "utf-8");
5162
8687
  server.app.get("*", (c) => c.html(indexHtml));
5163
8688
  }
5164
8689
  const { serve } = await import("@hono/node-server");