@dsh-mobile/mobile-remote 0.0.0-stage → 3.2.4

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 (41) hide show
  1. package/CHANGELOG.md +1069 -0
  2. package/CONTRIBUTING.md +59 -0
  3. package/FAQ.md +111 -0
  4. package/LICENSE +21 -0
  5. package/README.md +286 -2
  6. package/cordis.patch.yml +22 -0
  7. package/docs/00-/345/274/200/345/217/221/346/200/273/347/272/262.md +121 -0
  8. package/docs/01-PRD.md +148 -0
  9. package/docs/02-architecture.md +249 -0
  10. package/docs/03-api.md +834 -0
  11. package/docs/04-security.md +109 -0
  12. package/docs/05-test-cases.md +376 -0
  13. package/docs/06-install-run.md +336 -0
  14. package/docs/07-user-manual.md +70 -0
  15. package/docs/08-/346/211/251/345/261/225/345/274/200/345/217/221/346/214/207/345/215/227.md +86 -0
  16. package/docs/09-compatibility.md +201 -0
  17. package/docs/ARCHITECTURE-CURRENT.md +229 -0
  18. package/docs/BUILD-ENVIRONMENT.md +169 -0
  19. package/docs/FEATURE-PARITY.md +195 -0
  20. package/docs/PRIVACY-POLICY.md +65 -0
  21. package/docs/REA-UNDERSTANDING.md +246 -0
  22. package/docs/STORE-LAUNCH.md +130 -0
  23. package/docs/SUPPORT.md +42 -0
  24. package/docs/screenshots/01-home.png +0 -0
  25. package/docs/screenshots/02-notifications.png +0 -0
  26. package/docs/screenshots/03-sessions.png +0 -0
  27. package/docs/screenshots/04-chat.png +0 -0
  28. package/docs/screenshots/05-settings.png +0 -0
  29. package/docs/screenshots/06-new-session.png +0 -0
  30. package/docs/screenshots/pgy-appstore.jpg +0 -0
  31. package/docs/screenshots/pgy-mobile-app.jpg +0 -0
  32. package/docs/screenshots/pgy-pc-client.jpg +0 -0
  33. package/lib/account-usage.js +145 -0
  34. package/lib/auto-config.js +107 -0
  35. package/lib/client.js +303 -0
  36. package/lib/git-read-bundled-provider.js +255 -0
  37. package/lib/git-read-service.js +322 -0
  38. package/lib/index.js +7559 -0
  39. package/lib/session-title-cache.js +123 -0
  40. package/lib/session-title-refresh.js +261 -0
  41. package/package.json +62 -4
package/lib/client.js ADDED
@@ -0,0 +1,303 @@
1
+ // DSH Mobile Remote — 桌面 GUI 客户端模块
2
+ // 在 dsh 设置页注册"连接移动端设备"页:显示供手机 App 扫码连接的二维码。
3
+ //
4
+ // 打包形态:window.__ModuleLoader__.load({ id, factory })(dsh-client-modules 约定)。
5
+ // 手写 React.createElement(无 JSX/构建链),依赖由 dsh 客户端运行时提供。
6
+ // 数据来源:GET /m/api/qr-config(仅 loopback 可访问,返回地址+口令)。
7
+
8
+ window.__ModuleLoader__.load({
9
+ // 必须与 package.json 的 name 逐字相同:宿主按包名等待这个 id 注册,对不上就报
10
+ // "loaded without registering …"、设置页整块不显示(test/package-manifest.test.mjs 守着这条)。
11
+ id: "@dsh-mobile/mobile-remote",
12
+ factory: (require) => {
13
+ var module = { exports: {} };
14
+ var exports = module.exports;
15
+
16
+ var react = require("react");
17
+ var jsxRuntime = require("react/jsx-runtime");
18
+
19
+ var useState = react.useState;
20
+ var useEffect = react.useEffect;
21
+
22
+ /** 所需服务:slots(设置页 slot 注册)。 */
23
+ exports.inject = ["slots"];
24
+
25
+ var QR_CONFIG = "/m/api/qr-config";
26
+ var QR_IMAGE = "/m/qr.png";
27
+
28
+ var rowStyle = {
29
+ display: "flex",
30
+ alignItems: "center",
31
+ gap: "10px",
32
+ padding: "10px 0",
33
+ borderBottom: "1px solid var(--dsw-alias-divider-strong, rgba(128,128,128,.18))",
34
+ fontSize: "13.5px",
35
+ };
36
+ var btnStyle = {
37
+ marginLeft: "auto",
38
+ flex: "none",
39
+ padding: "4px 12px",
40
+ borderRadius: "8px",
41
+ border: "1px solid var(--dsw-alias-border-strong, rgba(128,128,128,.35))",
42
+ background: "none",
43
+ cursor: "pointer",
44
+ font: "inherit",
45
+ fontSize: "12px",
46
+ color: "inherit",
47
+ };
48
+
49
+ function toast(text) {
50
+ var el = document.getElementById("dsh-mr-toast");
51
+ if (!el) {
52
+ el = document.createElement("div");
53
+ el.id = "dsh-mr-toast";
54
+ el.style.cssText =
55
+ "position:fixed;left:50%;bottom:48px;transform:translateX(-50%);" +
56
+ "background:rgba(31,35,41,.92);color:#fff;border-radius:999px;" +
57
+ "padding:8px 16px;font-size:13px;z-index:9999;opacity:0;" +
58
+ "transition:opacity .2s;pointer-events:none;";
59
+ document.body.appendChild(el);
60
+ }
61
+ el.textContent = text;
62
+ el.style.opacity = "1";
63
+ clearTimeout(el._h);
64
+ el._h = setTimeout(function () {
65
+ el.style.opacity = "0";
66
+ }, 1600);
67
+ }
68
+
69
+ function fallbackCopy(text) {
70
+ // 非安全上下文(http 局域网 IP)下 Clipboard API 不可用,用 textarea + execCommand 降级
71
+ var ta = document.createElement("textarea");
72
+ ta.value = text;
73
+ ta.style.position = "fixed";
74
+ ta.style.opacity = "0";
75
+ document.body.appendChild(ta);
76
+ ta.select();
77
+ try {
78
+ document.execCommand("copy");
79
+ } catch (_) {
80
+ /* 忽略 */
81
+ }
82
+ ta.remove();
83
+ }
84
+
85
+ function copyText(text) {
86
+ var done = function () {
87
+ toast("已复制");
88
+ };
89
+ if (navigator.clipboard && window.isSecureContext) {
90
+ navigator.clipboard.writeText(text).then(
91
+ done,
92
+ function () {
93
+ fallbackCopy(text);
94
+ done();
95
+ }
96
+ );
97
+ } else {
98
+ fallbackCopy(text);
99
+ done();
100
+ }
101
+ }
102
+
103
+ /** 复制访问口令:60 秒后自动清空剪贴板(口令是唯一凭据,防其他应用读取;尽力而为)。 */
104
+ function copyToken(token) {
105
+ copyText(token);
106
+ setTimeout(function () {
107
+ try {
108
+ if (navigator.clipboard && window.isSecureContext) {
109
+ navigator.clipboard.readText().then(function (t) {
110
+ if (t === token) navigator.clipboard.writeText("");
111
+ });
112
+ }
113
+ } catch (_) {
114
+ /* 非安全上下文等场景尽力而为 */
115
+ }
116
+ }, 60000);
117
+ }
118
+
119
+ /**
120
+ * 构造二维码载荷:`DSHREMOTE|<电脑地址(含挂载路径)>|<访问口令>`。
121
+ *
122
+ * 纯函数(不触碰 DOM/React),导出供回归测试直接调用。
123
+ *
124
+ * 为什么需要 withMount 判断(PR #32 / 蔡严庆,2026-10-04):
125
+ * qr-config 响应的 urls **已自带挂载路径**——服务端 lib/index.js 的两条分支都拼了
126
+ * `${basePath}`(LAN 桥 `http://ip:3082/m`、回环 `http://ip:3080/m`)。旧实现在此处
127
+ * 再拼一次 mount,二维码里就成了 `/m/m`;App 端 `_pathOf()` 把整段路径原样当作请求
128
+ * 前缀,于是扫码连接一律 404(两种模式都中招,不只 LAN 桥)。
129
+ * 故:仅当目标 url 自身不含路径时才补 mount。
130
+ */
131
+ function buildQrPayload(data) {
132
+ var urls = Array.isArray(data && data.urls) ? data.urls : [];
133
+ var mount = String((data && data.basePath) || "/m").replace(/\/+$/, "");
134
+ var primary = urls.find(function (u) {
135
+ return !String(u).includes("127.0.0.1");
136
+ });
137
+ var qrTarget = primary ?? urls[0] ?? "http://127.0.0.1:3080";
138
+ var withMount = function (t) {
139
+ try {
140
+ var p = new URL(t).pathname.replace(/\/+$/, "");
141
+ return p ? t : t + mount;
142
+ } catch (e) {
143
+ return t + mount;
144
+ }
145
+ };
146
+ return "DSHREMOTE|" + withMount(qrTarget) + "|" + String((data && data.token) ?? "");
147
+ }
148
+ exports.buildQrPayload = buildQrPayload;
149
+
150
+ /**
151
+ * 设置页 section:连接移动端设备。
152
+ * 挂载后从 /m/api/qr-config 拉取地址与口令,渲染二维码 + 连接信息。
153
+ */
154
+ function MobileDeviceSection() {
155
+ var state = useState({ status: "loading", urls: [], token: "" });
156
+ var data = state[0];
157
+ var setData = state[1];
158
+
159
+ useEffect(function () {
160
+ var alive = true;
161
+ fetch(QR_CONFIG, { headers: { accept: "application/json" } })
162
+ .then(function (res) {
163
+ if (!res.ok) throw new Error("HTTP " + res.status);
164
+ return res.json();
165
+ })
166
+ .then(function (body) {
167
+ if (!alive) return;
168
+ var urls = Array.isArray(body.urls) ? body.urls : [];
169
+ // v3.0.0 review:path 从 qr-config 读取(不再硬编码 /m——插件挂载路径可配置)
170
+ setData({ status: "ready", urls: urls, token: String(body.token ?? ""), basePath: String(body.path || "/m") });
171
+ })
172
+ .catch(function (err) {
173
+ if (!alive) return;
174
+ setData({
175
+ status: "error",
176
+ urls: [],
177
+ token: "",
178
+ message: String(err?.message ?? err),
179
+ });
180
+ });
181
+ return function () {
182
+ alive = false;
183
+ };
184
+ }, []);
185
+
186
+ if (data.status === "loading") {
187
+ return jsxRuntime.jsx("div", { style: { padding: "20px 0", color: "var(--dsw-alias-label-secondary, #888)" }, children: "加载中…" });
188
+ }
189
+ if (data.status === "error") {
190
+ return jsxRuntime.jsx("div", {
191
+ style: { padding: "20px 0", color: "var(--dsw-alias-text-danger, #e5484d)" },
192
+ children: "无法获取连接信息:" + data.message + "(确认手机连接插件已启用,且路径为 /m)",
193
+ });
194
+ }
195
+
196
+ // v3.0.0 review:二维码 URL 携带挂载路径(App 端解析后使用,不再写死 /m)
197
+ // PR #32:路径拼接的坑与取舍见上方 buildQrPayload 注释
198
+ var mount = String(data.basePath || "/m").replace(/\/+$/, "");
199
+ var qrPayload = buildQrPayload(data);
200
+ var qrSrc = mount + "/qr.png?text=" + encodeURIComponent(qrPayload);
201
+
202
+ return jsxRuntime.jsx("div", {
203
+ style: { display: "flex", flexDirection: "column", gap: "6px", padding: "4px 0 16px" },
204
+ children: [
205
+ jsxRuntime.jsx("div", {
206
+ style: { fontSize: "13px", color: "var(--dsw-alias-label-secondary, #888)", lineHeight: "1.6" },
207
+ children: "用手机 DSH Remote App 扫描下方二维码,自动填入电脑地址与访问口令,即可远程发消息、看进度、收通知、审批决策。",
208
+ }),
209
+ data.token
210
+ ? null
211
+ : jsxRuntime.jsx("div", {
212
+ style: {
213
+ padding: "10px 12px",
214
+ borderRadius: "8px",
215
+ background: "rgba(229,72,77,.12)",
216
+ border: "1px solid rgba(229,72,77,.4)",
217
+ color: "var(--dsw-alias-text-danger, #e5484d)",
218
+ fontSize: "12.5px",
219
+ lineHeight: "1.6",
220
+ },
221
+ children:
222
+ "⚠️ 访问口令未启用:同一网络内任何设备都能连接并控制 agent,建议立即在 cordis.patch.yml 配置 authToken 后重启。",
223
+ }),
224
+ jsxRuntime.jsx("div", {
225
+ style: { display: "flex", flexDirection: "column", alignItems: "center", gap: "10px", padding: "14px 0" },
226
+ children: [
227
+ jsxRuntime.jsx("img", {
228
+ src: qrSrc,
229
+ alt: "连接二维码",
230
+ style: { width: 216, height: 216, borderRadius: "12px", background: "#fff", padding: 8 },
231
+ }),
232
+ jsxRuntime.jsx("div", {
233
+ style: { fontSize: "12px", color: "var(--dsw-alias-label-tertiary, #aaa)" },
234
+ children: "打开 App → 扫码连接 → 对准本二维码",
235
+ }),
236
+ ],
237
+ }),
238
+ jsxRuntime.jsx("div", { style: { fontSize: "13px", fontWeight: 600, margin: "8px 0 2px" }, children: "连接信息" }),
239
+ data.urls.map(function (u) {
240
+ return jsxRuntime.jsx(
241
+ "div",
242
+ {
243
+ style: rowStyle,
244
+ children: [
245
+ jsxRuntime.jsx("span", { style: { wordBreak: "break-all", fontFamily: "monospace", fontSize: "12.5px" }, children: u }),
246
+ jsxRuntime.jsx("button", { style: btnStyle, onClick: function () { copyText(u); }, children: "复制" }),
247
+ ],
248
+ },
249
+ u
250
+ );
251
+ }),
252
+ jsxRuntime.jsx(
253
+ "div",
254
+ {
255
+ style: rowStyle,
256
+ children: [
257
+ jsxRuntime.jsx("span", { children: "访问口令" }),
258
+ jsxRuntime.jsx(
259
+ "span",
260
+ {
261
+ style: { fontFamily: "monospace", fontSize: "12px", opacity: 0.75 },
262
+ children: data.token
263
+ ? data.token.slice(0, 6) + "…" + data.token.slice(-4)
264
+ : "未启用(局域网/内网环境)",
265
+ }
266
+ ),
267
+ data.token
268
+ ? jsxRuntime.jsx("button", {
269
+ style: btnStyle,
270
+ onClick: function () { copyToken(data.token); },
271
+ children: "复制",
272
+ })
273
+ : null,
274
+ ],
275
+ }
276
+ ),
277
+ jsxRuntime.jsx("div", {
278
+ style: { fontSize: "12px", color: "var(--dsw-alias-label-tertiary, #aaa)", marginTop: "6px" },
279
+ children: "二维码包含访问口令,仅在本机显示;请勿截屏转发。App 与手机浏览器(/m 网页)共用同一连接。",
280
+ }),
281
+ ],
282
+ });
283
+ }
284
+
285
+ /** 注册设置页 section(id: mobile-device)。 */
286
+ function apply(ctx) {
287
+ ctx.slots.inject("settings.section", function () {
288
+ return ctx.slots.register(
289
+ {
290
+ name: "settings.section",
291
+ id: "mobile-device",
292
+ order: 90,
293
+ label: "连接移动端设备",
294
+ },
295
+ MobileDeviceSection
296
+ );
297
+ });
298
+ }
299
+ exports.apply = apply;
300
+
301
+ return module.exports;
302
+ },
303
+ });
@@ -0,0 +1,255 @@
1
+ import { constants as fsConstants } from "node:fs";
2
+ import { realpath, open, lstat } from "node:fs/promises";
3
+ import { isAbsolute, relative, resolve, sep } from "node:path";
4
+ import { createHash } from "node:crypto";
5
+
6
+ const UNTRACKED_PREVIEW_MAX = 512 * 1024;
7
+ const SIGNATURE_SAMPLE_BYTES = 4096;
8
+ const readOnlyNoFollow = fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0);
9
+ function sameRegularFile(expected, opened) {
10
+ return expected.isFile() && opened.isFile() && expected.dev === opened.dev && expected.ino === opened.ino;
11
+ }
12
+ async function readPrefix(path, maximum, expected) {
13
+ const handle = await open(path, readOnlyNoFollow);
14
+ try {
15
+ if (!sameRegularFile(expected, await handle.stat())) throw new Error("file changed while opening preview");
16
+ const buffer = Buffer.alloc(maximum + 1);
17
+ const { bytesRead } = await handle.read(buffer, 0, maximum + 1, 0);
18
+ return { bytes: buffer.subarray(0, bytesRead), truncated: bytesRead > maximum };
19
+ } finally { await handle.close(); }
20
+ }
21
+ async function sampledFileSignature(path, info) {
22
+ const handle = await open(path, readOnlyNoFollow);
23
+ try {
24
+ if (!sameRegularFile(info, await handle.stat())) throw new Error("file changed while sampling worktree");
25
+ const first = Buffer.alloc(Math.min(SIGNATURE_SAMPLE_BYTES, info.size));
26
+ const firstRead = await handle.read(first, 0, first.length, 0);
27
+ let last = Buffer.alloc(0);
28
+ if (info.size > SIGNATURE_SAMPLE_BYTES) {
29
+ last = Buffer.alloc(SIGNATURE_SAMPLE_BYTES);
30
+ const read = await handle.read(last, 0, last.length, Math.max(0, info.size - last.length));
31
+ last = last.subarray(0, read.bytesRead);
32
+ }
33
+ return createHash("sha256").update(`${info.dev}:${info.ino}:${info.size}:${info.mtimeMs}:${info.ctimeMs}:`).update(first.subarray(0, firstRead.bytesRead)).update(last).digest("hex");
34
+ } finally { await handle.close(); }
35
+ }
36
+
37
+ function gitError(code, status, message = code) {
38
+ const error = new Error(message);
39
+ error.code = code;
40
+ error.status = status;
41
+ return error;
42
+ }
43
+
44
+ /** Bundled, read-only Git provider. Every command uses the host subprocess service. */
45
+ export function createBundledGitReadProvider(ctx) {
46
+ const get = (name) => {
47
+ try { return ctx.get?.(name); } catch { return undefined; }
48
+ };
49
+ const subprocess = () => get("subprocess") ?? ctx.subprocess;
50
+ const workspaces = () => (get("workspaceRegistry")?.list?.() ?? [])
51
+ .map((entry) => entry?.path).filter((path) => typeof path === "string" && path !== "");
52
+ const inside = (child, parent) => {
53
+ const value = relative(resolve(parent), resolve(child));
54
+ return value === "" || (value !== ".." && !value.startsWith(`..${sep}`) && !isAbsolute(value));
55
+ };
56
+ const assertWorkspace = async (path) => {
57
+ if (typeof path !== "string" || path === "") throw gitError("workspace-not-allowed", 403);
58
+ let canonical;
59
+ try { canonical = await realpath(path); } catch { throw gitError("workspace-not-allowed", 403); }
60
+ const roots = await Promise.all(workspaces().map((root) => realpath(root).catch(() => null)));
61
+ if (!roots.some((root) => root && inside(canonical, root))) throw gitError("workspace-not-allowed", 403);
62
+ return canonical;
63
+ };
64
+ const run = async (root, args, disableFilters = false, allowNoMatches = false) => {
65
+ root = await assertWorkspace(root);
66
+ const executor = subprocess();
67
+ if (!executor?.spawn) throw gitError("git-provider-unavailable", 503);
68
+ const noHooksPath = process.platform === "win32" ? "NUL" : "/dev/null";
69
+ let filterOverrides = [];
70
+ if (disableFilters) {
71
+ const names = await run(root, ["config", "--null", "--name-only", "--get-regexp", "^filter\\..*\\.(clean|process)$"], false, true);
72
+ filterOverrides = names.split("\0").filter(Boolean).flatMap((name) => ["-c", `${name}=`]);
73
+ }
74
+ const child = executor.spawn({
75
+ argv: [
76
+ process.platform === "win32" ? "git.exe" : "git",
77
+ "-c", "core.fsmonitor=false",
78
+ "-c", `core.hooksPath=${noHooksPath}`,
79
+ ...filterOverrides,
80
+ "-C", root,
81
+ "--no-optional-locks",
82
+ ...args,
83
+ ],
84
+ cwd: root,
85
+ // Prevent ambient Git repository/config overrides from redirecting a
86
+ // session-authorized read. Undefined values are seam tombstones.
87
+ env: {
88
+ GIT_TERMINAL_PROMPT: "0",
89
+ GCM_INTERACTIVE: "never",
90
+ GIT_DIR: undefined,
91
+ GIT_WORK_TREE: undefined,
92
+ GIT_INDEX_FILE: undefined,
93
+ GIT_COMMON_DIR: undefined,
94
+ GIT_OBJECT_DIRECTORY: undefined,
95
+ GIT_ALTERNATE_OBJECT_DIRECTORIES: undefined,
96
+ GIT_CONFIG: undefined,
97
+ GIT_CONFIG_PARAMETERS: undefined,
98
+ GIT_CONFIG_COUNT: "0",
99
+ // Trace destinations open files even for otherwise read-only Git commands.
100
+ ...Object.fromEntries(Object.keys(process.env).filter((key) => /^GIT_TRACE(?:2)?(?:_|$)/.test(key)).map((key) => [key, undefined])),
101
+ GIT_TRACE: undefined,
102
+ GIT_TRACE2: undefined,
103
+ GIT_TRACE2_EVENT: undefined,
104
+ GIT_TRACE2_PERF: undefined,
105
+ },
106
+ stdio: { stdin: "ignore", stdout: { maxBytes: 8 * 1024 * 1024 }, stderr: { maxBytes: 1024 * 1024 } },
107
+ graceMs: 10_000,
108
+ });
109
+ const done = await child.done;
110
+ const stdoutResult = await child.collected?.stdout?.readFrom?.(0);
111
+ const stderrResult = await child.collected?.stderr?.readFrom?.(0);
112
+ if (stdoutResult?.lossy || stderrResult?.lossy) {
113
+ throw gitError("git-output-too-large", 413);
114
+ }
115
+ const stdout = stdoutResult?.text ?? "";
116
+ const stderr = stderrResult?.text ?? "";
117
+ if (done?.exitCode !== 0) {
118
+ if (allowNoMatches && done?.exitCode === 1) return "";
119
+ if (/not a git repository/i.test(stderr)) throw gitError("not-git-repository", 404);
120
+ throw gitError("git-command-failed", 400);
121
+ }
122
+ return stdout;
123
+ };
124
+ const repositoryRoot = async (cwd) => {
125
+ const allowed = await assertWorkspace(cwd);
126
+ const root = (await run(allowed, ["rev-parse", "--show-toplevel"])).trim();
127
+ return assertWorkspace(root);
128
+ };
129
+ return {
130
+ contractVersion: "1.0.0",
131
+ capabilities() {
132
+ const available = Boolean(subprocess()?.spawn) && workspaces().length > 0;
133
+ return { available, reason: available ? null : !subprocess()?.spawn ? "git-provider-unavailable" : "workspace-registry-unavailable" };
134
+ },
135
+ repositoryRoot,
136
+ async refSignature(root) {
137
+ let refs = "";
138
+ try { refs = await run(root, ["show-ref", "--head", "--dereference"]); } catch (error) { if (error?.code !== "git-command-failed") throw error; }
139
+ return createHash("sha256").update(refs).digest("hex");
140
+ },
141
+ async repositoryInfo(root) {
142
+ let currentBranch = null, headOid = null;
143
+ try { currentBranch = (await run(root, ["symbolic-ref", "--quiet", "HEAD"])).trim() || null; } catch (error) { if (error?.code !== "git-command-failed") throw error; }
144
+ try { headOid = (await run(root, ["rev-parse", "--verify", "HEAD"])).trim() || null; } catch (error) { if (error?.code !== "git-command-failed") throw error; }
145
+ return { ...(headOid ? { headOid } : {}), ...(currentBranch ? { currentBranch } : {}), detached: Boolean(headOid && !currentBranch), empty: !headOid };
146
+ },
147
+ async resolveTip(root, ref) {
148
+ return (await run(root, ["rev-parse", "--verify", `${ref}^{commit}`])).trim();
149
+ },
150
+ async graph(root, { refs, offset, limit }) {
151
+ if (refs.length === 0) return [];
152
+ const text = await run(root, ["log", "--topo-order", "--date-order", `--skip=${offset}`, `--max-count=${limit}`, "--decorate=full", "--format=%H%x1f%P%x1f%an%x1f%at%x1f%s%x1f%D%x00", ...refs]);
153
+ return text.split("\0").map((record) => record.replace(/^[\r\n]+|[\r\n]+$/g, "")).filter(Boolean).map((record) => {
154
+ const [oid, parents, author, timestamp, subject, decorations] = record.split("\x1f");
155
+ return { oid, parents: parents ? parents.split(" ") : [], author, timestamp: Number(timestamp) || 0, subject, refs: decorations ? decorations.split(",").map((value) => value.trim()).filter(Boolean) : [] };
156
+ });
157
+ },
158
+ async commit(root, oid) {
159
+ if (typeof oid !== "string" || !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(oid)) throw gitError("invalid-oid", 400);
160
+ const metadata = (await run(root, ["show", "-s", "--format=%H%x1f%P%x1f%an%x1f%at%x1f%B%x00", oid])).split("\0")[0].split("\x1f");
161
+ const [hash, parentText, author, timestamp, ...messageParts] = metadata;
162
+ const diffBase = parentText ? [parentText.split(" ")[0], hash] : ["--root", hash];
163
+ const statusParts = (await run(root, ["diff-tree", "--no-commit-id", "-r", "-M", "--name-status", "-z", ...diffBase])).split("\0");
164
+ const files = [];
165
+ for (let index = 0; index < statusParts.length;) {
166
+ const code = statusParts[index++];
167
+ if (!code) continue;
168
+ const renamed = code.startsWith("R") || code.startsWith("C");
169
+ const oldPath = renamed ? statusParts[index++] : undefined;
170
+ const path = statusParts[index++];
171
+ if (!path) break;
172
+ const statuses = { A: "added", M: "modified", D: "deleted", R: "renamed", C: "copied", T: "type-changed" };
173
+ files.push({ path, ...(oldPath ? { oldPath } : {}), status: statuses[code[0]] ?? "modified" });
174
+ }
175
+ const statParts = (await run(root, ["diff-tree", "--no-commit-id", "-r", "-M", "--numstat", "-z", ...diffBase])).split("\0");
176
+ const stats = new Map();
177
+ for (let index = 0; index < statParts.length;) {
178
+ const record = statParts[index++];
179
+ if (!record) continue;
180
+ const firstTab = record.indexOf("\t");
181
+ const secondTab = record.indexOf("\t", firstTab + 1);
182
+ if (firstTab < 0 || secondTab < 0) continue;
183
+ const added = record.slice(0, firstTab);
184
+ const deleted = record.slice(firstTab + 1, secondTab);
185
+ let path = record.slice(secondTab + 1);
186
+ if (!path) { index++; path = statParts[index++] ?? ""; }
187
+ stats.set(path, { binary: added === "-" || deleted === "-", additions: added === "-" ? null : Number(added), deletions: deleted === "-" ? null : Number(deleted) });
188
+ }
189
+ for (const file of files) Object.assign(file, stats.get(file.path) ?? { binary: false, additions: 0, deletions: 0 });
190
+ return { oid: hash, parents: parentText ? parentText.split(" ") : [], author, timestamp: Number(timestamp) || 0, message: messageParts.join("\x1f").trim(), files };
191
+ },
192
+ async worktree(root) {
193
+ const text = await run(root, ["status", "--porcelain=v1", "-z", "--untracked-files=all"], true);
194
+ const parts = text.split("\0"); const entries = [];
195
+ for (let i = 0; i < parts.length;) {
196
+ const record = parts[i++]; if (!record) continue;
197
+ const code = record.slice(0, 2); let path = record.slice(3); let oldPath;
198
+ if (/[RC]/.test(code)) { oldPath = parts[i++] ?? ""; }
199
+ const status = code.includes("U") || code === "AA" || code === "DD" ? "conflicted" : code === "??" ? "untracked" : "modified";
200
+ entries.push({ path, ...(oldPath ? { oldPath } : {}), status, conflicted: status === "conflicted", index: code[0] !== " " && code !== "??", worktree: code[1] !== " " && code !== "??" });
201
+ }
202
+ let signatureMaterial = text;
203
+ for (const entry of entries) {
204
+ if (entry.status !== "untracked" && !entry.worktree) continue;
205
+ try { const target = resolve(root, entry.path); const info = await lstat(target); signatureMaterial += `\\0${entry.path}:${info.isSymbolicLink() ? "symlink" : info.isFile() ? await sampledFileSignature(target, info) : "special"}`; } catch { signatureMaterial += `\\0${entry.path}:missing`; }
206
+ }
207
+ try { signatureMaterial += await run(root, ["--literal-pathspecs", "diff", "--raw", "-z", "--no-abbrev", "HEAD"], true); } catch (error) { if (error?.code !== "git-command-failed") throw error; }
208
+ try { signatureMaterial += await run(root, ["--literal-pathspecs", "diff", "--raw", "-z", "--no-abbrev", "--cached"], true); } catch (error) { if (error?.code !== "git-command-failed") throw error; }
209
+ const signature = createHash("sha256").update(signatureMaterial).digest("hex");
210
+ return { entries, signature };
211
+ },
212
+ async worktreePreview(root, kind, path) {
213
+ const args = ["--literal-pathspecs", "diff", "--unified=999999", "--no-ext-diff", "--no-textconv", "--no-color", "--binary"];
214
+ if (kind === "staged") args.push("--cached");
215
+ args.push("--", path);
216
+ if (kind === "untracked") {
217
+ try {
218
+ const target = resolve(root, path); const info = await lstat(target);
219
+ if (info.isSymbolicLink()) return { diff: "", binary: false, additions: null, deletions: null, notice: "symlink preview omitted" };
220
+ if (!info.isFile()) return { diff: "", binary: false, additions: null, deletions: null, notice: "special file preview omitted" };
221
+ const { bytes, truncated } = await readPrefix(target, UNTRACKED_PREVIEW_MAX, info);
222
+ const binary = bytes.includes(0);
223
+ return { diff: binary ? "" : bytes.toString("utf8"), binary, truncated, additions: null, deletions: null, ...(binary ? { notice: "binary preview omitted" } : {}) };
224
+ } catch { return { diff: "", binary: false, additions: 0, deletions: 0, notice: "unavailable" }; }
225
+ }
226
+ return { diff: await run(root, args, true), binary: false, additions: null, deletions: null };
227
+ },
228
+ async commitPreview(root, oid, path) {
229
+ const commit = await this.commit(root, oid);
230
+ if (!commit.parents.length) return { diff: await run(root, ["--literal-pathspecs", "diff-tree", "--root", "--no-commit-id", "-p", "-r", "--unified=999999", "--no-ext-diff", "--no-textconv", "--no-color", "--binary", oid, "--", path]), binary: false };
231
+ return { diff: await run(root, ["--literal-pathspecs", "diff", "--unified=999999", "--no-ext-diff", "--no-textconv", "--no-color", "--binary", `${oid}^1`, oid, "--", path]), binary: false };
232
+ },
233
+ async branches(root) {
234
+ const text = await run(root, ["for-each-ref", "--format=%(HEAD)%09%(refname)%09%(objectname)%09%(upstream:short)%00", "refs/heads", "refs/remotes"]);
235
+ const rows = text.split("\0").map((record) => record.replace(/^[\r\n]+|[\r\n]+$/g, "")).filter(Boolean);
236
+ const branches = [];
237
+ for (const row of rows) {
238
+ const [head, ref, oid, upstream = ""] = row.split("\t");
239
+ if (ref.endsWith("/HEAD")) continue;
240
+ const local = ref.startsWith("refs/heads/");
241
+ let ahead = 0, behind = 0;
242
+ if (local && upstream) {
243
+ const counts = (await run(root, ["rev-list", "--left-right", "--count", `${ref}...${upstream}`])).trim().split(/\s+/).map(Number);
244
+ [ahead, behind] = counts;
245
+ }
246
+ branches.push({
247
+ name: ref, displayName: ref.replace(/^refs\/(?:heads|remotes)\//, ""), oid,
248
+ kind: local ? "local" : "remote", current: local && head === "*",
249
+ tracking: local && upstream ? `refs/remotes/${upstream}` : null, ahead, behind,
250
+ });
251
+ }
252
+ return branches;
253
+ },
254
+ };
255
+ }