larness 0.5.1 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/apps/server/dist/{managed-Cw3MVilO.js → address-DpgJ0siq.js} +317 -183
  2. package/apps/server/dist/{args-CrKTPT06.js → args-BdJc1CBU.js} +29 -22
  3. package/apps/server/dist/cli.js +28 -7
  4. package/apps/server/dist/client-CBpatu1B.js +28 -0
  5. package/apps/server/dist/{client-D_Ni3Zpx.js → client-CoxHAiNW.js} +1 -1
  6. package/apps/server/dist/doctor-CGNZt_v3.js +1 -0
  7. package/apps/server/dist/{doctor-CE6cONuz.js → doctor-rpwPrkoS.js} +4 -3
  8. package/apps/server/dist/doctor.js +1 -1
  9. package/apps/server/dist/index.js +1442 -500
  10. package/apps/server/dist/{inspect-XgAc84F9.js → inspect-DUe_-Yma.js} +89 -1
  11. package/apps/server/dist/{lifecycle-C3KV3-Ax.js → lifecycle-Ck4LRKft.js} +7 -4
  12. package/apps/server/dist/managed-CpNf_iJZ.js +191 -0
  13. package/apps/server/dist/status-B6kiOT0f.js +94 -0
  14. package/apps/server/dist/status-C0hriYPD.js +681 -0
  15. package/apps/server/dist/status.js +1 -58
  16. package/apps/server/dist/{supervisor-IYDKL4iU.js → supervisor-BvHyiN7Z.js} +3 -2
  17. package/apps/server/dist/tui.js +5 -5
  18. package/apps/server/dist/unlock-hrRXYx4L.js +87 -0
  19. package/apps/server/drizzle/0039_user_input_requests.sql +20 -0
  20. package/apps/server/drizzle/meta/0039_snapshot.json +5907 -0
  21. package/apps/server/drizzle/meta/_journal.json +7 -0
  22. package/apps/web/dist/assets/{FileEditor-DnQa6Owc.js → FileEditor-2VPjs-RQ.js} +1 -1
  23. package/apps/web/dist/assets/{FileViewer-DKlF-CWF.js → FileViewer-CZcKFZJT.js} +1 -1
  24. package/apps/web/dist/assets/{cssMode-C9KmpsHc.js → cssMode-D-Rled60.js} +1 -1
  25. package/apps/web/dist/assets/{editor.api-BwfHyHQ6.js → editor.api-C3oaU0qj.js} +1 -1
  26. package/apps/web/dist/assets/{freemarker2-D41RlIQ5.js → freemarker2-D50E-mj1.js} +1 -1
  27. package/apps/web/dist/assets/{handlebars-D-7R6ic0.js → handlebars-_Xg_xwtq.js} +1 -1
  28. package/apps/web/dist/assets/{html-CUME4rt-.js → html-BPuGWYaH.js} +1 -1
  29. package/apps/web/dist/assets/{htmlMode-8w7WLhnL.js → htmlMode-CwmSqoNt.js} +1 -1
  30. package/apps/web/dist/assets/{index-BOS3UrP1.js → index-DPZpqlAG.js} +2 -2
  31. package/apps/web/dist/assets/{javascript-_3pdDG34.js → javascript-iFH4qFsX.js} +1 -1
  32. package/apps/web/dist/assets/{jsonMode-DiqocFCf.js → jsonMode-On0Ct3VU.js} +1 -1
  33. package/apps/web/dist/assets/{liquid-j0FoiTXN.js → liquid-BX3WY7Z7.js} +1 -1
  34. package/apps/web/dist/assets/{lspLanguageFeatures-Zj7K2sG4.js → lspLanguageFeatures-BXlOyN1U.js} +1 -1
  35. package/apps/web/dist/assets/main-Bm74KyWu.css +1 -0
  36. package/apps/web/dist/assets/main-GXToakQe.js +157 -0
  37. package/apps/web/dist/assets/{mdx-CGQ8Cw6J.js → mdx-Bzq19TjL.js} +1 -1
  38. package/apps/web/dist/assets/{monaco-CyMA3azg.js → monaco-DCdDhoJ6.js} +3 -3
  39. package/apps/web/dist/assets/{python-BtY34Z9A.js → python-CaZSKPNI.js} +1 -1
  40. package/apps/web/dist/assets/{razor-CzYHpLv5.js → razor-CH1GgILn.js} +1 -1
  41. package/apps/web/dist/assets/{tsMode-GZx3VEv9.js → tsMode-BWGjCNkx.js} +1 -1
  42. package/apps/web/dist/assets/{typescript-CAfvuTDQ.js → typescript-D2FxAaol.js} +1 -1
  43. package/apps/web/dist/assets/{workers-C5BOxOmH.js → workers-BUPNyHSF.js} +1 -1
  44. package/apps/web/dist/assets/{xml-BGX4mtH7.js → xml-nOgwOHKV.js} +1 -1
  45. package/apps/web/dist/assets/{yaml-B2AgBtJB.js → yaml-CyK2AZ1G.js} +1 -1
  46. package/apps/web/dist/index.html +1 -1
  47. package/docs/guides/install.md +3 -0
  48. package/package.json +1 -1
  49. package/apps/server/dist/address-D0ZG5qR4.js +0 -97
  50. package/apps/server/dist/doctor-sPRlI92N.js +0 -1
  51. package/apps/server/dist/status-CV_zWfs6.js +0 -62
  52. package/apps/web/dist/assets/main-DZIruO5x.js +0 -157
  53. package/apps/web/dist/assets/main-gq3n_vn8.css +0 -1
@@ -1,12 +1,12 @@
1
- import { An as OriginUrlSchema, Jn as FilePathSchema, tr as MAX_EDITABLE_FILE_BYTES } from "./inspect-XgAc84F9.js";
1
+ import { hr as MAX_EDITABLE_FILE_BYTES, rr as FilePathSchema, zn as OriginUrlSchema } from "./inspect-DUe_-Yma.js";
2
2
  import { createHash, randomUUID } from "node:crypto";
3
- import { constants, existsSync, readFileSync, realpathSync, statSync, watch } from "node:fs";
3
+ import { constants, createReadStream, statSync, watch } from "node:fs";
4
4
  import path from "node:path";
5
5
  import { z } from "zod";
6
6
  import { execFile, spawn } from "node:child_process";
7
7
  import { StringDecoder } from "node:string_decoder";
8
8
  import { promisify } from "node:util";
9
- import { access, lstat, mkdir, open, opendir, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
9
+ import { access, link, lstat, mkdir, open, opendir, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
10
10
  import { applyPatch, diffLines, parsePatch } from "diff";
11
11
  import os, { tmpdir } from "node:os";
12
12
  // ../../packages/resources/src/commands/redactor.ts
@@ -1607,6 +1607,187 @@ async function saveEditableFile(root, input, hooks) {
1607
1607
  if (!result) reject("INTERNAL", "File save did not produce a result");
1608
1608
  return result;
1609
1609
  }
1610
+ /**
1611
+ * Read one regular file as raw bytes. Binary content is expected here, so the
1612
+ * only opinions are: no symbolic links, no directories, and a caller-supplied
1613
+ * ceiling. Identity is re-checked after the read, like `readEditableFile`.
1614
+ */
1615
+ async function readRawFile(root, relative, maxBytes) {
1616
+ try {
1617
+ const normalized = normalizeFilePath(relative);
1618
+ const target = await resolveFilePath(root, normalized);
1619
+ if (!(await lstat(target)).isFile()) reject("VALIDATION_ERROR", "Only regular files can be downloaded");
1620
+ const fd = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
1621
+ try {
1622
+ const before = await fd.stat();
1623
+ if (!before.isFile()) reject("VALIDATION_ERROR", "Only regular files can be downloaded");
1624
+ if (before.size > maxBytes) reject("PAYLOAD_TOO_LARGE", "File exceeds transfer limit");
1625
+ const bytes = Buffer.alloc(before.size + 1);
1626
+ let size = 0;
1627
+ while (size < bytes.length) {
1628
+ const read = await fd.read(bytes, size, bytes.length - size, size);
1629
+ if (read.bytesRead === 0) break;
1630
+ size += read.bytesRead;
1631
+ }
1632
+ if (size > maxBytes) reject("PAYLOAD_TOO_LARGE", "File exceeds transfer limit");
1633
+ const snapshot = await lstat(await resolveFilePath(root, normalized));
1634
+ const after = await fd.stat();
1635
+ if (snapshot.ino !== before.ino || snapshot.dev !== before.dev || snapshot.size !== size || before.size !== after.size || before.mtimeMs !== after.mtimeMs) reject("CONFLICT", "File identity changed while reading");
1636
+ const buffer = bytes.subarray(0, size);
1637
+ return {
1638
+ path: normalized,
1639
+ realPath: target,
1640
+ bytes: buffer,
1641
+ version: hashContent(buffer),
1642
+ size,
1643
+ mtimeMs: before.mtimeMs
1644
+ };
1645
+ } finally {
1646
+ await fd.close();
1647
+ }
1648
+ } catch (error) {
1649
+ filesystemError(error);
1650
+ }
1651
+ }
1652
+ function hashFile(target) {
1653
+ return new Promise((resolvePromise, rejectPromise) => {
1654
+ const hash = createHash("sha256");
1655
+ let size = 0;
1656
+ createReadStream(target).on("data", (chunk) => {
1657
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
1658
+ hash.update(bytes);
1659
+ size += bytes.length;
1660
+ }).on("error", rejectPromise).on("end", () => resolvePromise({
1661
+ version: hash.digest("hex"),
1662
+ size
1663
+ }));
1664
+ });
1665
+ }
1666
+ async function identity(target) {
1667
+ try {
1668
+ return await lstat(target);
1669
+ } catch (error) {
1670
+ if (z.object({ code: z.literal("ENOENT") }).safeParse(error).success) return null;
1671
+ filesystemError(error);
1672
+ }
1673
+ }
1674
+ /** Control characters are not valid in a portable file name. */
1675
+ function hasControlCharacters(value) {
1676
+ for (const character of value) {
1677
+ const code = character.codePointAt(0) ?? 0;
1678
+ if (code < 32 || code === 127) return true;
1679
+ }
1680
+ return false;
1681
+ }
1682
+ /**
1683
+ * Write an uploaded buffer to `relative`. Creation uses `link` (or an exclusive
1684
+ * open on filesystems without hard links) so an existing path is never
1685
+ * clobbered; replacement requires the caller's `expectedVersion` and re-checks
1686
+ * it immediately before `rename`. Temporary files are removed on failure when
1687
+ * their identity still matches.
1688
+ */
1689
+ async function writeUploadedFile(root, relative, bytes, hooks = {}) {
1690
+ if (bytes.length > 26214400) reject("PAYLOAD_TOO_LARGE", "File exceeds transfer limit");
1691
+ let created = false;
1692
+ let result;
1693
+ let temporary;
1694
+ let temporaryIdentity;
1695
+ let failed = false;
1696
+ let failure;
1697
+ try {
1698
+ const normalized = normalizeFilePath(relative);
1699
+ if (normalized === ".") reject("VALIDATION_ERROR", "A file path is required");
1700
+ const segments = normalized.split("/");
1701
+ const name = segments.at(-1) ?? "";
1702
+ if (!name || name === "." || name === ".." || /[\\/:*?"<>|]/.test(name) || hasControlCharacters(name)) reject("VALIDATION_ERROR", "Invalid file name");
1703
+ const parentPath = await resolveFilePath(root, segments.slice(0, -1).join("/") || ".");
1704
+ if (!(await lstat(parentPath)).isDirectory()) reject("NOT_FOUND", "Target directory is unavailable");
1705
+ const target = path.join(parentPath, name);
1706
+ const existing = await identity(target);
1707
+ if (existing && !existing.isFile()) reject("CONFLICT", "Target is not a regular file");
1708
+ let previousVersion;
1709
+ if (existing) {
1710
+ const current = await hashFile(target);
1711
+ previousVersion = current.version;
1712
+ if (hooks.expectedVersion === void 0) throw new FileManagerError("CONFLICT", "Target already exists", {
1713
+ currentVersion: current.version,
1714
+ size: current.size
1715
+ });
1716
+ if (hooks.expectedVersion !== current.version) throw new FileManagerError("VERSION_CONFLICT", "File version changed", { currentVersion: current.version });
1717
+ } else if (hooks.expectedVersion !== void 0) throw new FileManagerError("VERSION_CONFLICT", "File no longer exists", { currentVersion: hashContent(Buffer.alloc(0)) });
1718
+ const temporaryName = hooks.temporaryName ?? `.larness-save-${randomUUID()}`;
1719
+ if (!/^\.larness-save-[a-zA-Z0-9_-]+$/.test(temporaryName)) reject("INTERNAL", "Invalid upload operation identity");
1720
+ temporary = path.join(parentPath, temporaryName);
1721
+ hooks.assertFence?.();
1722
+ const fd = await open(temporary, "wx", 384);
1723
+ try {
1724
+ temporaryIdentity = await fd.stat();
1725
+ hooks.assertFence?.();
1726
+ await fd.writeFile(bytes);
1727
+ await fd.sync();
1728
+ } finally {
1729
+ await fd.close();
1730
+ }
1731
+ if (existing) {
1732
+ const current = await hashFile(target);
1733
+ if (current.version !== previousVersion) throw new FileManagerError("VERSION_CONFLICT", "File version changed", { currentVersion: current.version });
1734
+ hooks.assertFence?.();
1735
+ await rename(temporary, target);
1736
+ temporaryIdentity = void 0;
1737
+ } else {
1738
+ hooks.assertFence?.();
1739
+ try {
1740
+ await link(temporary, target);
1741
+ } catch (error) {
1742
+ const code = z.object({ code: z.string() }).safeParse(error);
1743
+ if (code.success && code.data.code === "EEXIST") throw new FileManagerError("CONFLICT", "Target already exists");
1744
+ if (!code.success || ![
1745
+ "EPERM",
1746
+ "ENOTSUP",
1747
+ "EOPNOTSUPP"
1748
+ ].includes(code.data.code)) throw error;
1749
+ let out;
1750
+ try {
1751
+ out = await open(target, "wx", 384);
1752
+ await out.writeFile(bytes);
1753
+ await out.sync();
1754
+ } catch (writeError) {
1755
+ await out?.close();
1756
+ out = void 0;
1757
+ const writeCode = z.object({ code: z.string() }).safeParse(writeError);
1758
+ if (writeCode.success && writeCode.data.code === "EEXIST") throw new FileManagerError("CONFLICT", "Target already exists");
1759
+ throw writeError;
1760
+ } finally {
1761
+ await out?.close();
1762
+ }
1763
+ }
1764
+ created = true;
1765
+ }
1766
+ result = {
1767
+ path: normalized,
1768
+ realPath: target,
1769
+ version: hashContent(bytes),
1770
+ size: bytes.length,
1771
+ created,
1772
+ ...previousVersion === void 0 ? {} : { previousVersion }
1773
+ };
1774
+ } catch (error) {
1775
+ failed = true;
1776
+ failure = error;
1777
+ }
1778
+ if (temporary !== void 0) try {
1779
+ const current = await identity(temporary);
1780
+ if (current !== null) {
1781
+ if (!temporaryIdentity || current.ino !== temporaryIdentity.ino || current.dev !== temporaryIdentity.dev) throw new FileManagerError("RESOURCE_UNAVAILABLE", "Temporary upload identity changed", void 0, true);
1782
+ await rm(temporary);
1783
+ }
1784
+ } catch {
1785
+ throw new FileManagerError("RESOURCE_UNAVAILABLE", "File upload cleanup requires reconciliation", void 0, true);
1786
+ }
1787
+ if (failed) filesystemError(failure);
1788
+ if (!result) reject("INTERNAL", "File upload did not produce a result");
1789
+ return result;
1790
+ }
1610
1791
  const CursorSchema = z.object({
1611
1792
  directory: z.string(),
1612
1793
  revision: z.string(),
@@ -2045,18 +2226,65 @@ function snapshotOf(status, raw) {
2045
2226
  })).digest("hex");
2046
2227
  }
2047
2228
  function parseLog(raw) {
2048
- return raw.split("").map((record) => record.trim()).filter(Boolean).map((record) => {
2049
- const [hash = "", shortHash = "", author = "", email = "", timestamp = "0", subject = ""] = record.split("");
2229
+ return raw.split("\0").filter((record) => record !== "").map((record) => {
2230
+ const fields = record.split("");
2231
+ const [hash = "", shortHash = "", parents = "", author = "", email = "", timestamp = "0"] = fields;
2232
+ const refs = fields[6] ?? "";
2233
+ const subject = fields.slice(7).join("");
2050
2234
  return {
2051
2235
  hash,
2052
2236
  shortHash,
2053
2237
  author,
2054
2238
  email,
2055
2239
  timestamp: Number(timestamp) * 1e3,
2056
- subject
2240
+ subject,
2241
+ parents: parents.split(" ").filter(Boolean),
2242
+ refs: refs.split(",").map((ref) => ref.trim()).filter(Boolean)
2057
2243
  };
2058
2244
  });
2059
2245
  }
2246
+ const COMMIT_FILE_STATUS = {
2247
+ A: "added",
2248
+ M: "modified",
2249
+ D: "deleted",
2250
+ R: "renamed",
2251
+ C: "copied",
2252
+ T: "typechange"
2253
+ };
2254
+ /**
2255
+ * Parses `git diff --name-status -z`. Records are NUL terminated and a rename /
2256
+ * copy record carries two paths, so the stream cannot be split into lines.
2257
+ */
2258
+ function parseCommitFiles(raw) {
2259
+ const tokens = raw.split("\0");
2260
+ const files = [];
2261
+ for (let index = 0; index < tokens.length; index++) {
2262
+ const code = tokens[index] ?? "";
2263
+ if (!code) continue;
2264
+ const letter = code[0] ?? "?";
2265
+ if (letter === "R" || letter === "C") {
2266
+ const origPath = tokens[index + 1] ?? "";
2267
+ const pathValue = tokens[index + 2] ?? "";
2268
+ index += 2;
2269
+ if (!pathValue) continue;
2270
+ files.push({
2271
+ path: pathValue,
2272
+ origPath: origPath || null,
2273
+ status: letter === "R" ? "renamed" : "copied"
2274
+ });
2275
+ continue;
2276
+ }
2277
+ const pathValue = tokens[index + 1] ?? "";
2278
+ index += 1;
2279
+ if (!pathValue) continue;
2280
+ files.push({
2281
+ path: pathValue,
2282
+ origPath: null,
2283
+ status: COMMIT_FILE_STATUS[letter] ?? "unknown"
2284
+ });
2285
+ }
2286
+ return files;
2287
+ }
2060
2288
  function parseBranches(raw) {
2061
2289
  return raw.split("\n").map((record) => record.trim()).filter(Boolean).map((record) => {
2062
2290
  const [name = "", head = "", current = ""] = record.split(" ");
@@ -2249,189 +2477,95 @@ var ManagedPty = class {
2249
2477
  return this.#stop;
2250
2478
  }
2251
2479
  };
2252
- // src/dev-web/paths.ts
2253
- const Manifest = z.object({
2254
- dependencies: z.record(z.string(), z.string()).optional(),
2255
- optionalDependencies: z.record(z.string(), z.string()).optional(),
2256
- peerDependencies: z.record(z.string(), z.string()).optional()
2480
+ // src/ipc/protocol.ts
2481
+ const MAX_FRAME_BYTES = 1048576;
2482
+ const DEFAULT_IDLE_TIMEOUT_MS = 18e5;
2483
+ var IpcError = class extends Error {
2484
+ code;
2485
+ constructor(code, message) {
2486
+ super(message);
2487
+ this.name = "IpcError";
2488
+ this.code = code;
2489
+ }
2490
+ };
2491
+ const RequestEnvelopeSchema = z.object({
2492
+ id: z.string().min(1).max(128),
2493
+ method: z.string().min(1).max(64),
2494
+ params: z.unknown().optional()
2257
2495
  });
2258
- const contains = (root, file) => file === root || file.startsWith(root + path.sep);
2259
- function webRoots(webRoot) {
2260
- const roots = /* @__PURE__ */ new Set();
2261
- const visit = (directory) => {
2262
- if (!existsSync(directory)) return;
2263
- const root = realpathSync(directory);
2264
- if (roots.has(root)) return;
2265
- roots.add(root);
2266
- const manifestPath = path.join(root, "package.json");
2267
- if (!existsSync(manifestPath)) return;
2268
- const pkg = Manifest.parse(JSON.parse(readFileSync(manifestPath, "utf8")));
2269
- for (const name of Object.keys({
2270
- ...pkg.dependencies,
2271
- ...pkg.optionalDependencies,
2272
- ...pkg.peerDependencies
2273
- })) {
2274
- let base = root;
2275
- for (;;) {
2276
- const candidate = path.join(base, "node_modules", name);
2277
- if (existsSync(candidate)) {
2278
- visit(candidate);
2279
- break;
2280
- }
2281
- const parent = path.dirname(base);
2282
- if (parent === base) break;
2283
- base = parent;
2284
- }
2496
+ const HelloParamsSchema = z.object({
2497
+ token: z.string().min(1).max(256),
2498
+ client: z.string().min(1).max(64),
2499
+ pid: z.int().positive().optional()
2500
+ }).strict();
2501
+ const InitApplyParamsSchema = z.object({
2502
+ host: z.string().min(1).max(255).optional(),
2503
+ port: z.int().min(1).max(65535).optional(),
2504
+ publicUrl: OriginUrlSchema.nullable().optional(),
2505
+ channel: z.enum(["stable", "beta"]).optional()
2506
+ }).strict();
2507
+ const LogsTailParamsSchema = z.object({ lines: z.int().min(1).max(500).optional() }).strict();
2508
+ const AuditTailParamsSchema = z.object({ limit: z.int().min(1).max(200).optional() }).strict();
2509
+ const ShutdownParamsSchema = z.object({
2510
+ confirm: z.literal(true),
2511
+ source: z.enum(["cli", "tui"]).optional()
2512
+ }).strict();
2513
+ const PairingListParamsSchema = z.object({ status: z.enum([
2514
+ "pending",
2515
+ "approved",
2516
+ "denied",
2517
+ "expired",
2518
+ "enrollment_pending",
2519
+ "redeemed"
2520
+ ]).optional() }).strict();
2521
+ const PairingApproveParamsSchema = z.object({
2522
+ requestId: z.string().min(1).max(128),
2523
+ decision: z.enum(["allow_once", "trust"])
2524
+ }).strict();
2525
+ const PairingDenyParamsSchema = z.object({ requestId: z.string().min(1).max(128) }).strict();
2526
+ const DeviceRevokeParamsSchema = z.object({ deviceId: z.string().min(1).max(128) }).strict();
2527
+ const SessionRevokeParamsSchema = z.object({ sessionId: z.string().min(1).max(128) }).strict();
2528
+ function errorResponse(id, error) {
2529
+ if (error instanceof IpcError) return {
2530
+ id,
2531
+ ok: false,
2532
+ error: {
2533
+ code: error.code,
2534
+ message: error.message
2285
2535
  }
2286
2536
  };
2287
- visit(webRoot);
2288
- visit(path.resolve(webRoot, "../../packages/ui"));
2289
- visit(path.resolve(webRoot, "../../packages/shared"));
2290
- visit(path.join(webRoot, "node_modules/vite"));
2291
- return [...roots];
2292
- }
2293
- function isDevPath(pathname) {
2294
- return /^\/(?:@vite(?:\/|$)|@react-refresh(?:\/|$)|@fs(?:\/|$)|@id(?:\/|$)|src(?:\/|$)|node_modules(?:\/|$)|__vite|__open-in-editor|_larness(?:\/|$))/.test(pathname);
2295
- }
2296
- function permittedPath(rawUrl, webRoot, roots) {
2297
- try {
2298
- const rawPath = rawUrl.split("?")[0] ?? "";
2299
- const decoded = decodeURIComponent(rawPath);
2300
- if (!decoded.startsWith("/") || decoded.startsWith("//") || decoded.includes("%") || decoded.includes("\\") || decoded.includes("\0")) return false;
2301
- if (decoded.split("/").some((s) => s === ".." || s === "." || s.startsWith(".env") || s === ".git" || /^(?:config\.json|master\.key|larness\.(?:db|lock)|vite\.config\..*|.*\.log)$/.test(s))) return false;
2302
- if (/^\/(?:api|ws|_larness)(?:\/|$)/.test(decoded) || decoded.startsWith("/__open-in-editor") || decoded.startsWith("/__vite")) return false;
2303
- const file = decoded.startsWith("/@fs/") ? path.normalize(decoded.slice(process.platform === "win32" ? 5 : 4)) : path.join(webRoot, decoded);
2304
- if (existsSync(file)) return roots.some((root) => contains(realpathSync(root), realpathSync(file)));
2305
- let ancestor = file;
2306
- while (!existsSync(ancestor)) {
2307
- const parent = path.dirname(ancestor);
2308
- if (parent === ancestor) return false;
2309
- ancestor = parent;
2537
+ return {
2538
+ id,
2539
+ ok: false,
2540
+ error: {
2541
+ code: "INTERNAL",
2542
+ message: "Internal IPC error"
2310
2543
  }
2311
- return roots.some((root) => contains(realpathSync(root), realpathSync(ancestor)));
2312
- } catch {
2313
- return false;
2314
- }
2544
+ };
2315
2545
  }
2316
- // src/dev-web/control.ts
2317
- const HMR_PATH = "/_larness/dev/hmr";
2318
- const NONCE_MARKER = "LARNESS_DEV_RESPONSE_NONCE";
2319
- var DevWebUnavailable = class extends Error {
2320
- code = "DEV_WEB_UNAVAILABLE";
2321
- constructor() {
2322
- super("开发运行环境已停止,请重新启动 TUI");
2323
- }
2324
- };
2325
- var EntryConfigError = class extends Error {
2326
- constructor(origin, port) {
2327
- const canonical = new URL(OriginUrlSchema.parse(origin));
2328
- const targetPort = Number(canonical.port || (canonical.protocol === "https:" ? 443 : 80));
2329
- super(`浏览器地址是 ${canonical.origin},Server 监听端口是 ${port}。请关闭实例,一次性将 config.json 的 server.port 对齐为 ${targetPort},保留 publicUrl 和其他配置;若端口来自环境变量,请调整对应环境变量。`);
2330
- }
2331
- };
2332
- const devWebCache = (generation) => path.join(tmpdir(), `larness-vite-cache-${z.uuid().parse(generation)}`);
2333
- const DevWebTargetSchema = z.strictObject({
2334
- generation: z.uuid(),
2335
- host: z.literal("127.0.0.1"),
2336
- port: z.int().min(1).max(65535)
2337
- });
2338
- const DevWebReadySchema = DevWebTargetSchema.extend({ type: z.literal("dev-web.ready") });
2339
- const DevWebAttachSchema = DevWebTargetSchema.extend({ type: z.literal("dev-web.attach") });
2340
- const DevWebAttachedSchema = z.strictObject({
2341
- type: z.literal("dev-web.attached"),
2342
- generation: z.uuid()
2343
- });
2344
- z.strictObject({
2345
- type: z.literal("dev-web.start"),
2346
- generation: z.uuid(),
2347
- origin: OriginUrlSchema
2348
- });
2349
- var DevWebControl = class {
2350
- child;
2351
- generation;
2352
- current = null;
2353
- closed = false;
2354
- constructor(child, generation) {
2355
- this.child = child;
2356
- this.generation = generation;
2357
- }
2358
- get target() {
2359
- return this.current;
2360
- }
2361
- accept(child, message) {
2362
- const parsed = DevWebReadySchema.safeParse(message);
2363
- if (this.closed || child !== this.child || !parsed.success || parsed.data.generation !== this.generation) return false;
2364
- const { type: _type, ...target } = parsed.data;
2365
- if (this.current && this.current.port !== target.port) return false;
2366
- this.current = target;
2367
- return true;
2368
- }
2369
- close() {
2370
- this.closed = true;
2371
- this.current = null;
2372
- }
2373
- };
2374
- // src/dev-web/managed.ts
2375
- function managedWebFiles(serverRoot, target) {
2376
- const webRoot = realpathSync(path.resolve(serverRoot, "../../apps/web"));
2546
+ function shortHash(dataDir) {
2547
+ return createHash("sha256").update(dataDir).digest("hex").slice(0, 16);
2548
+ }
2549
+ function resolveIpcAddress(dataDir, platform = process.platform, tempRoot = tmpdir()) {
2550
+ if (platform === "win32") return {
2551
+ path: `\\\\.\\pipe\\larness-${shortHash(dataDir)}`,
2552
+ kind: "pipe",
2553
+ tempDirectory: null
2554
+ };
2555
+ const localPath = path.join(dataDir, "ipc", "larness.sock");
2556
+ if (Buffer.byteLength(localPath, "utf8") <= 100) return {
2557
+ path: localPath,
2558
+ kind: "unix",
2559
+ tempDirectory: null
2560
+ };
2561
+ const directory = path.join(tempRoot, `larness-${shortHash(dataDir)}`);
2377
2562
  return {
2378
- webRoot,
2379
- roots: [...webRoots(webRoot), realpathSync(devWebCache(target.generation))]
2563
+ path: path.join(directory, "larness.sock"),
2564
+ kind: "unix",
2565
+ tempDirectory: directory
2380
2566
  };
2381
2567
  }
2382
- function receiveDevWebTarget(timeoutMs = 25e3, signal) {
2383
- if (!process.send) return Promise.reject(/* @__PURE__ */ new Error("开发转发需要受管控制通道"));
2384
- return new Promise((resolve, reject) => {
2385
- const timer = setTimeout(() => finish(/* @__PURE__ */ new Error("开发控制通道超时")), timeoutMs);
2386
- const disconnect = () => finish(/* @__PURE__ */ new Error("开发控制通道已关闭"));
2387
- const abort = () => finish(/* @__PURE__ */ new Error("启动已取消"));
2388
- const message = (value) => {
2389
- const parsed = DevWebAttachSchema.safeParse(value);
2390
- if (!parsed.success) {
2391
- finish(/* @__PURE__ */ new Error("开发控制消息无效"));
2392
- return;
2393
- }
2394
- const { type: _type, ...target } = parsed.data;
2395
- finish(null, target);
2396
- };
2397
- const finish = (error, target) => {
2398
- clearTimeout(timer);
2399
- process.off("message", message);
2400
- process.off("disconnect", disconnect);
2401
- signal?.removeEventListener("abort", abort);
2402
- if (error) reject(error);
2403
- else if (target) resolve(target);
2404
- };
2405
- process.once("message", message);
2406
- process.once("disconnect", disconnect);
2407
- signal?.addEventListener("abort", abort, { once: true });
2408
- if (signal?.aborted) abort();
2409
- });
2410
- }
2411
- function waitChildMessage(child, parse, signal, phase = "Server") {
2412
- return new Promise((resolve, reject) => {
2413
- const timer = setTimeout(() => finish(/* @__PURE__ */ new Error("开发子进程就绪超时")), 25e3);
2414
- const fail = () => finish(/* @__PURE__ */ new Error(`${phase} 未就绪即退出 (code=${child.exitCode ?? "none"}, signal=${child.signalCode ?? "none"})`));
2415
- const abort = () => finish(/* @__PURE__ */ new Error("启动已取消"));
2416
- const message = (value) => {
2417
- const parsed = parse(value);
2418
- if (parsed === null) finish(/* @__PURE__ */ new Error("开发子进程控制消息无效"));
2419
- else finish(null, parsed);
2420
- };
2421
- const finish = (error, value) => {
2422
- clearTimeout(timer);
2423
- child.off("message", message);
2424
- child.off("exit", fail);
2425
- child.off("error", fail);
2426
- signal?.removeEventListener("abort", abort);
2427
- if (error) reject(error);
2428
- else if (value !== void 0) resolve(value);
2429
- };
2430
- child.on("message", message);
2431
- child.once("exit", fail);
2432
- child.once("error", fail);
2433
- signal?.addEventListener("abort", abort, { once: true });
2434
- if (signal?.aborted) abort();
2435
- });
2568
+ function ipcTokenPath(dataDir) {
2569
+ return path.join(dataDir, "ipc", "token");
2436
2570
  }
2437
- export { resolveWindowsExecutable as $, normalizeFilePath as A, isIgnoredFile as B, validateGitPath as C, encodeEditableContent as D, FileManagerError as E, DEFAULT_IGNORED as F, PathGuardError as G, readTextFile as H, FileError as I, resolveInsideRoot as J, canonicalDirectory as K, applyPatch$1 as L, resolveFilePath as M, saveEditableFile as N, fileEntryVersion as O, searchFiles as P, stopCommandGroup as Q, editTextFile as R, snapshotOf as S, scanWatchPath as T, searchCode as U, listFiles as V, writeTextFile as W, groupAlive as X, MAX_COMMAND_OUTPUT_BYTES as Y, runCommand as Z, parseBranches as _, DevWebControl as a, windowsTcpListeners as at, runGit as b, EntryConfigError as c, powerShellEncodedCommand as ct, devWebCache as d, windowsLaunch as et, isDevPath as f, gitPrefix as g, GitError as h, DevWebAttachedSchema as i, terminateProcessTree as it, readEditableFile as j, listDirectory as k, HMR_PATH as l, windowsPowerShell as lt, ManagedPty as m, receiveDevWebTarget as n, processCommandLine as nt, DevWebTargetSchema as o, commandEnvironment as ot, permittedPath as p, isInsideRoot as q, waitChildMessage as r, processSnapshot as rt, DevWebUnavailable as s, powerShellArguments as st, managedWebFiles as t, processAlive as tt, NONCE_MARKER as u, OutputRedactor as ut, parseLog as v, createDirectoryWatcher as w, scopeStatusToPrefix as x, parseStatus as y, hashContent as z };
2571
+ export { canonicalDirectory as $, scanWatchPath as A, searchFiles as B, parseLog as C, snapshotOf as D, scopeStatusToPrefix as E, normalizeFilePath as F, editTextFile as G, DEFAULT_IGNORED as H, readEditableFile as I, listFiles as J, hashContent as K, readRawFile as L, encodeEditableContent as M, fileEntryVersion as N, validateGitPath as O, listDirectory as P, PathGuardError as Q, resolveFilePath as R, parseCommitFiles as S, runGit as T, FileError as U, writeUploadedFile as V, applyPatch$1 as W, searchCode as X, readTextFile as Y, writeTextFile as Z, errorResponse as _, OutputRedactor as _t, DeviceRevokeParamsSchema as a, stopCommandGroup as at, gitPrefix as b, IpcError as c, processAlive as ct, PairingApproveParamsSchema as d, terminateProcessTree as dt, isInsideRoot as et, PairingDenyParamsSchema as f, windowsTcpListeners as ft, ShutdownParamsSchema as g, windowsPowerShell as gt, SessionRevokeParamsSchema as h, powerShellEncodedCommand as ht, DEFAULT_IDLE_TIMEOUT_MS as i, runCommand as it, FileManagerError as j, createDirectoryWatcher as k, LogsTailParamsSchema as l, processCommandLine as lt, RequestEnvelopeSchema as m, powerShellArguments as mt, resolveIpcAddress as n, MAX_COMMAND_OUTPUT_BYTES as nt, HelloParamsSchema as o, resolveWindowsExecutable as ot, PairingListParamsSchema as p, commandEnvironment as pt, isIgnoredFile as q, AuditTailParamsSchema as r, groupAlive as rt, InitApplyParamsSchema as s, windowsLaunch as st, ipcTokenPath as t, resolveInsideRoot as tt, MAX_FRAME_BYTES as u, processSnapshot as ut, ManagedPty as v, parseStatus as w, parseBranches as x, GitError as y, saveEditableFile as z };
@@ -20,7 +20,8 @@ const COMMANDS = /* @__PURE__ */ new Set([
20
20
  "tui",
21
21
  "status",
22
22
  "logs",
23
- "doctor"
23
+ "doctor",
24
+ "unlock"
24
25
  ]);
25
26
  const DEFAULT_LOG_LINES = 200;
26
27
  const MAX_LOG_LINES = 1e3;
@@ -30,43 +31,48 @@ function parseLines(value) {
30
31
  if (lines < 1 || lines > 1e3) throw new UsageError(`--lines expects an integer between 1 and ${MAX_LOG_LINES}`);
31
32
  return lines;
32
33
  }
34
+ function baseCommand(name) {
35
+ return {
36
+ name,
37
+ json: false,
38
+ lines: DEFAULT_LOG_LINES,
39
+ daemon: false,
40
+ follow: false,
41
+ force: false,
42
+ allowLive: false
43
+ };
44
+ }
33
45
  function parseArgs(argv) {
34
46
  const [first, ...rest] = argv;
35
47
  if (first === void 0 || first === "help" || first === "--help" || first === "-h") {
36
48
  if (rest.length > 0) throw new UsageError(`unexpected arguments after help: ${rest.join(" ")}`);
37
- return {
38
- name: "help",
39
- json: false,
40
- lines: DEFAULT_LOG_LINES,
41
- daemon: false,
42
- follow: false
43
- };
49
+ return baseCommand("help");
44
50
  }
45
51
  if (first === "--version" || first === "-v") {
46
52
  if (rest.length > 0) throw new UsageError("--version does not accept arguments");
47
- return {
48
- name: "version",
49
- json: false,
50
- lines: DEFAULT_LOG_LINES,
51
- daemon: false,
52
- follow: false
53
- };
53
+ return baseCommand("version");
54
54
  }
55
55
  if (!COMMANDS.has(first)) throw new UnknownCommandError(first);
56
56
  const command = first;
57
- const parsed = {
58
- name: command,
59
- json: false,
60
- lines: DEFAULT_LOG_LINES,
61
- daemon: false,
62
- follow: false
63
- };
57
+ const parsed = baseCommand(command);
64
58
  for (let index = 0; index < rest.length; index += 1) {
65
59
  const arg = rest[index] ?? "";
66
60
  if (command === "status" && arg === "--json") {
67
61
  parsed.json = true;
68
62
  continue;
69
63
  }
64
+ if (command === "unlock" && arg === "--json") {
65
+ parsed.json = true;
66
+ continue;
67
+ }
68
+ if (command === "unlock" && arg === "--force") {
69
+ parsed.force = true;
70
+ continue;
71
+ }
72
+ if (command === "unlock" && arg === "--allow-live") {
73
+ parsed.allowLive = true;
74
+ continue;
75
+ }
70
76
  if (command === "logs" && arg === "--daemon") {
71
77
  parsed.daemon = true;
72
78
  continue;
@@ -87,6 +93,7 @@ function parseArgs(argv) {
87
93
  if (arg.startsWith("-")) throw new UsageError(`unknown option for ${command}: ${arg}`);
88
94
  throw new UsageError(`unexpected argument for ${command}: ${arg}`);
89
95
  }
96
+ if (parsed.allowLive && !parsed.force) throw new UsageError("--allow-live requires --force");
90
97
  return parsed;
91
98
  }
92
99
  export { UsageError as n, parseArgs as r, UnknownCommandError as t };