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

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 (73) hide show
  1. package/CHANGELOG.md +1273 -0
  2. package/CONTRIBUTING.md +59 -0
  3. package/FAQ.md +115 -0
  4. package/LICENSE +21 -0
  5. package/README.md +293 -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 +882 -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 +349 -0
  14. package/docs/07-user-manual.md +92 -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/10-remote-access-and-launch-plan.md +216 -0
  18. package/docs/11-remote-relay-guide.md +82 -0
  19. package/docs/APP-ENCRYPTION-DESCRIPTION.md +50 -0
  20. package/docs/APP-ENCRYPTION-DESCRIPTION.pdf +0 -0
  21. package/docs/ARCHITECTURE-CURRENT.md +229 -0
  22. package/docs/AUDIT-2026-11-node.md +181 -0
  23. package/docs/AUDIT-2026-11.md +167 -0
  24. package/docs/BRAND-ASSETS.md +142 -0
  25. package/docs/BUILD-ENVIRONMENT.md +180 -0
  26. package/docs/FEATURE-PARITY.md +195 -0
  27. package/docs/PRIVACY-POLICY.en.md +143 -0
  28. package/docs/PRIVACY-POLICY.md +143 -0
  29. package/docs/REA-UNDERSTANDING.md +246 -0
  30. package/docs/STORE-LAUNCH.md +278 -0
  31. package/docs/STORE-LISTING.md +150 -0
  32. package/docs/SUPPORT.md +43 -0
  33. package/docs/TERMS-OF-SERVICE.en.md +70 -0
  34. package/docs/TERMS-OF-SERVICE.md +70 -0
  35. package/docs/screenshots/01-home.png +0 -0
  36. package/docs/screenshots/02-notifications.png +0 -0
  37. package/docs/screenshots/03-sessions.png +0 -0
  38. package/docs/screenshots/04-chat.png +0 -0
  39. package/docs/screenshots/05-settings.png +0 -0
  40. package/docs/screenshots/06-new-session.png +0 -0
  41. package/docs/screenshots/07-connect.png +0 -0
  42. package/docs/screenshots/pgy-appstore.jpg +0 -0
  43. package/docs/screenshots/pgy-mobile-app.jpg +0 -0
  44. package/docs/screenshots/pgy-pc-client.jpg +0 -0
  45. package/lib/account-usage-query.js +278 -0
  46. package/lib/account-usage.js +145 -0
  47. package/lib/api-helpers.js +333 -0
  48. package/lib/auto-config.js +107 -0
  49. package/lib/client.js +586 -0
  50. package/lib/config.js +211 -0
  51. package/lib/git-read-bundled-provider.js +255 -0
  52. package/lib/git-read-service.js +322 -0
  53. package/lib/host-compat.js +133 -0
  54. package/lib/http-util.js +69 -0
  55. package/lib/index.js +5729 -0
  56. package/lib/push.js +73 -0
  57. package/lib/rate-limit.js +46 -0
  58. package/lib/relay/connector.js +300 -0
  59. package/lib/relay/crypto.js +117 -0
  60. package/lib/relay/devices.js +138 -0
  61. package/lib/relay/identity.js +60 -0
  62. package/lib/relay/mux.js +411 -0
  63. package/lib/relay/noise.js +178 -0
  64. package/lib/relay/pairing.js +64 -0
  65. package/lib/relay/phone.js +114 -0
  66. package/lib/relay/serve.js +105 -0
  67. package/lib/rpc-adapter.js +88 -0
  68. package/lib/session-list.js +77 -0
  69. package/lib/session-title-cache.js +123 -0
  70. package/lib/session-title-refresh.js +261 -0
  71. package/lib/timeline.js +476 -0
  72. package/lib/turn-outline.js +289 -0
  73. package/package.json +62 -4
package/lib/config.js ADDED
@@ -0,0 +1,211 @@
1
+ /**
2
+ * 插件配置 schema 与两个会随配置一起被读取的默认预算常量。
3
+ * 从 lib/index.js 原样拆出(行为不变);index.js 重新导出,对外导入路径不变。
4
+ */
5
+ import z from "@deepseek-ai/schemastery";
6
+
7
+ /**
8
+ * 会话枚举预算的默认值(毫秒,issue #27)。
9
+ *
10
+ * **必须小于客户端的请求超时**:App 对 `/sessions` 用的是 `getJson` 的默认超时 **15 秒**
11
+ * (`dsh-mobile-app/lib/api.dart`)。若服务端预算更大,冷首轮落在 15–30 秒时会出现
12
+ * 「服务端最终返回 200、客户端已经先放弃」——用户既拿不到列表、也拿不到明确失败。
13
+ * 取 12 秒 = 15 秒 − 3 秒余量(网络往返 + ~110KB JSON 序列化)。
14
+ *
15
+ * 与 `Config.enumerationBudgetMs` 的 schema 默认保持一致;运行时另有兜底:宿主把**原始**
16
+ * config 传给 `apply()`(schema 默认值不在这里生效),缺字段时必须回落到本常量,
17
+ * 否则 `undefined - elapsed` 会得到 NaN、`setTimeout(NaN)` 立即触发 → 冷启动误判超时。
18
+ */
19
+ export const DEFAULT_ENUMERATION_BUDGET_MS = 12_000;
20
+
21
+ /**
22
+ * 启动预热里标题折叠的**有限生命期**(毫秒,issue #28 复核 BLOCKING 2)。
23
+ *
24
+ * 它**不是**响应路径的 1.5 秒预算:预热要跑完整轮折叠才有意义,但绝不能像响应路径那样在
25
+ * 预算到点后把 run 提升为「永久后台」——一次挂住的预热会让之后健康的请求一直 join 这个坏 run、
26
+ * 只拿到短码。到点即由 `release()` 退休该 run(若无其它等待者),健康请求随后可重新开始。
27
+ */
28
+ export const DEFAULT_WARM_UP_TITLE_BUDGET_MS = 10_000;
29
+
30
+ /** 插件配置 schema。 */
31
+ export const Config = z.object({
32
+ /** 移动页挂载路径:单段、以 / 开头。禁止 "/"(会劫持桌面 SPA fallback)。 */
33
+ path: z.string().pattern(/^\/[a-zA-Z0-9_-]+$/).default("/m"),
34
+ /**
35
+ * 访问口令;空 = 关闭认证(信任网络层)。建议 ≥16 字符随机串。
36
+ * 写 `"@auto"`(v3.2.4,随插件自带的 cordis.patch.yml 使用)= 首次启动自动生成强口令并保存到
37
+ * `~/.dsh/mobile-remote/auth-token`,之后复用;启动日志与 DSH 设置页「连接移动端设备」都会显示它。
38
+ */
39
+ authToken: z.string().default(""),
40
+ /** 认证 cookie 名。 */
41
+ cookieName: z.string().default("dsh_mobile_token"),
42
+ /**
43
+ * 额外可信主机(Host 校验白名单扩展):内网穿透/中继场景显式声明。
44
+ * 例如 frp 中转时 App 通过 `http://<VPS地址>:3080` 访问,请求的 Host 头是 VPS 地址,
45
+ * 默认 Host 校验会拒绝;把 VPS 地址(IP 或域名,不带端口)加进此列表即可放行。
46
+ * 注意:仅在确信中继通道安全(加密隧道)+ 开启 authToken 的前提下配置。
47
+ */
48
+ trustedHosts: z.array(z.string()).default([]),
49
+ /**
50
+ * 配置了 `trustedHosts`(= 经隧道/中继对外提供服务)时,是否仍允许 `/qr-config`(含口令)与
51
+ * `/qr.png` 应答。默认 `false`:中继形态下,转发到本机的连接在 TCP 层也来自 127.0.0.1,
52
+ * 与桌面设置页的真实本机请求无法区分,放行等于把口令发给任何能触达中继的人。
53
+ * 关闭后桌面设置页的二维码不可用,改为从 cordis.patch.yml 手动取口令输入 App。
54
+ * 仅当隧道/反代终结在**另一台机器**、本机服务只被本机访问时才可置 `true`。
55
+ */
56
+ qrConfigBehindRelay: z.boolean().default(false),
57
+ /**
58
+ * 启动时把「手机 App 要填的地址 + 口令」打印到终端(stderr)。默认开启。
59
+ * 口令只在 `authToken: "@auto"` 自动生成时才会打印;你自己写进配置的口令永远不进日志。
60
+ * 走 stderr 而不是 `ctx.logger.info`:宿主默认把 info 级别日志藏起来,这条信息本来就是给人看的。
61
+ */
62
+ printConnectionInfo: z.boolean().default(true),
63
+ /** 登录会话有效期(毫秒),默认 30 天。 */
64
+ sessionTtlMs: z.number().default(30 * 24 * 3600 * 1000),
65
+ /**
66
+ * 会话枚举(`sessionQuery.listSessions`)自己的时间预算(毫秒,默认 12 秒)。
67
+ *
68
+ * issue #27:枚举是端点的**核心数据**,不能用标题折叠的 1.5s 预算去掐——宿主刚重启时
69
+ * 内核语料状态是冷的(维护者 note 793 实测全量 `persistence.stat()` 约 22 秒),枚举必然
70
+ * 超过 1.5s,于是冷启动首次请求直接 504,用户拿不到列表。标题折叠仍保留 ≤1.5s 预算
71
+ * (超预算的会话先用短码兜底、随后后台预热)。此预算只用于**兜底**:真慢到这个量级
72
+ * 仍显式 504,不会无限挂住唯一入口。
73
+ *
74
+ * **取值必须小于客户端超时**(App 对 `/sessions` 是 15 秒):服务端要先于客户端给出结论,
75
+ * 否则会出现「服务端最终 200、客户端已放弃」。理由与余量见 `DEFAULT_ENUMERATION_BUDGET_MS`。
76
+ */
77
+ enumerationBudgetMs: z.number().min(0).default(DEFAULT_ENUMERATION_BUDGET_MS),
78
+ /**
79
+ * 是否在插件初始化时预热会话列表路径(默认 `true`,issue #28)。
80
+ *
81
+ * 冷路径(语料枚举 + revision 扫描 + 标题折叠)会长时间占住宿主的事件循环——实测同一窗口内
82
+ * 不碰语料的 `/m/api/bootstrap` 被推迟 **8.48 秒**,宿主重启后第一次 `/sessions` 要等
83
+ * 10–60 秒,远超 App 的 15 秒请求超时;而且预算/定时器在这种阻塞下**无法准时触发**。
84
+ * 预热把这份冷代价挪到用户请求之前:初始化后主动跑一遍与请求**同一条**路径(枚举 +
85
+ * 标题折叠,复用同一套缓存与 single-flight),用户即使恰好撞上也只是加入同一轮工作。
86
+ * 置 `false` 则完全不预热,行为与不开启时一致。
87
+ */
88
+ warmUpOnStart: z.boolean().default(true),
89
+ /** 启动预热里标题折叠的生命期(毫秒,默认 10 秒,issue #28);语义见 `DEFAULT_WARM_UP_TITLE_BUDGET_MS`。 */
90
+ warmUpTitleBudgetMs: z.number().min(0).default(DEFAULT_WARM_UP_TITLE_BUDGET_MS),
91
+ /**
92
+ * `/turn-outline` 的有界等待上限(毫秒,默认 5000)。
93
+ *
94
+ * 该值来自 issue #25 的性能前置实测(单会话冷折叠最坏 1.8 s,见
95
+ * `reports/25-cold-fold-20261009.md`),从**请求到达**时开始计时、包含排队时间;
96
+ * 超时即向活连接回明确的降级结果,而真正未结束的观察仍占住执行槽直到结束。
97
+ * 暴露成配置只为在契约门禁里用更短的截止时间做**端点级**定时测试。
98
+ */
99
+ turnOutlineTimeoutMs: z.number().default(5000),
100
+ /** SSE 连接数上限。 */
101
+ maxConnections: z.number().default(16),
102
+ /**
103
+ * 推送桥(Phase 2):agent 完成/需要回答/失败 → 手机系统通知。
104
+ * 每个条目一个通道;format:
105
+ * serverchan — POST url(形如 https://sctapi.ftqq.com/<SendKey>.send 或
106
+ * Server酱³ 官方 https://<uid>.push.ft07.com/send/<sendkey>.send),form: title/desp
107
+ * ntfy — 配置填主题地址(形如 https://ntfy.sh/<topic>);实际请求为
108
+ * json POST 到服务器根地址 + body 内带 topic(v3.1.4 修正,
109
+ * 见 ntfyPublish:发到主题地址会被当纯文本,标题丢失)
110
+ * bark — POST url(形如 https://api.day.app/<key>),json: { title, body }
111
+ * generic — POST url,json: { kind, title, detail, sessionId, time }
112
+ */
113
+ pushUrls: z
114
+ .array(z.object({ name: z.string().default("push"), url: z.string().required(), format: z.string().default("generic") }))
115
+ .default([]),
116
+ /** 推送节流:同会话同类型的最小间隔(毫秒),默认 60 秒。 */
117
+ pushCooldownMs: z.number().default(60_000),
118
+ /**
119
+ * 真结束判定宽限(毫秒,v2.8.0):agent 转为 idle 后需稳定此时长、
120
+ * 且无 active goal,才判定"对话真正结束"并通知——多轮大任务不再
121
+ * 每完成一个子轮次就推一次"任务完成"。
122
+ */
123
+ doneGraceMs: z.number().default(15_000),
124
+ /**
125
+ * 推送内容级别(v2.6.0):
126
+ * minimal — 默认。只推事件类型 + 会话短码,会话标题/错误详情等核心内容
127
+ * 不进第三方推送通道(Server酱/ntfy/Bark 等)。
128
+ * standard — 含会话标题与事件详情(旧行为)。第三方服务会看到这些内容,
129
+ * 仅在信任通道时开启。
130
+ */
131
+ pushContent: z.string().default("minimal"),
132
+ /**
133
+ * 登录失败限流(v2.6.0,仅 authToken 启用时生效):
134
+ * 窗口内失败次数 ≥ maxFailures → 429,窗口过后自动恢复;认证成功重置计数。
135
+ */
136
+ rateLimit: z
137
+ .object({
138
+ maxFailures: z.number().default(10),
139
+ windowMs: z.number().default(60_000),
140
+ blockMs: z.number().default(60_000),
141
+ })
142
+ .default({}),
143
+ /**
144
+ * LAN 桥(v2.9.0):桌面版(dsh-plugin-desktop)强制 webserver 只听回环,手机无法直连;
145
+ * 插件在 DSH 进程内自建第二个 HTTP 监听,把 `${path}` 前缀请求流式转发到回环 webserver。
146
+ * 仅暴露移动端面(不转发 /api 网关、qr-config/qr.png);未配置 authToken 时拒绝启动。
147
+ * 默认关闭;启用后手机访问 `http://<电脑局域网IP>:<port>/m`(App 扫码/手动填均可)。
148
+ *
149
+ * `enabled` 除了 true/false,还可写 `"auto"`(v3.2.4,随插件自带的 cordis.patch.yml 使用):
150
+ * 只在 webserver 只听回环(桌面版)时才开桥;web 版 webserver 已听 0.0.0.0,不需要也不会开。
151
+ */
152
+ lanBridge: z
153
+ .object({
154
+ enabled: z.union([z.boolean(), z.const("auto")]).default(false),
155
+ // v2.9.0 review(M#7):port 合法区间 1-65535(0=随机端口会与上报地址错位),host 非空
156
+ port: z.number().min(1).max(65535).default(3080),
157
+ host: z.string().min(1).default("0.0.0.0"),
158
+ })
159
+ .default({}),
160
+ /**
161
+ * 端到端加密中继(v3.3):让手机在**任何网络**下连到这台电脑,手机与电脑都不用装 VPN 软件。
162
+ * 电脑只**出站**连接 `urls` 里的中继(不开任何入站端口);中继只转发密文,看不到内容。
163
+ * 默认关闭——没有可用的中继地址就没有意义。设备用桌面设置页里的一次性二维码配对,可单独撤销。
164
+ * 设计与威胁模型见 docs/10-remote-access-and-launch-plan.md,中继服务见 relay/。
165
+ */
166
+ relay: z
167
+ .object({
168
+ enabled: z.boolean().default(false),
169
+ /** 中继地址(必须 wss://;仅本机测试允许回环地址的 ws://),可配多个做备份。 */
170
+ urls: z.array(z.string()).default([]),
171
+ /** 配对时显示给手机的电脑名称;空则用主机名。 */
172
+ name: z.string().default(""),
173
+ })
174
+ .default({}),
175
+ /**
176
+ * 审批/问询呈现策略(v3.1.3,issue #9——手机在线时桌面端不再弹审批框):
177
+ * both(默认)——桌面 GUI 与手机同时收到审批/问询待办,任一端先答即生效、另一端
178
+ * 自动收卡(对齐 v3.1.1 帧桥广播体验)。要求内核 0.1.2-rc.1+(桌面 v2.0.5+,
179
+ * 即 approval/request 瀑布 + $events 远程事件通道);旧宿主自动降级 mobile。
180
+ * mobile —— 手机在线时由手机独占应答(v3.1.2 行为),离线交桌面 GUI。外出远程用。
181
+ * desktop —— 一律交给桌面 GUI(手机不弹审批/问询卡)。常驻电脑前、不远程审批用。
182
+ * 桌面端/手机端均无应答时保持超时 fail-close(FAQ「问询/审批弹窗类」+ docs/09 §2.1)。
183
+ */
184
+ approvalMode: z
185
+ .union([z.const("both"), z.const("mobile"), z.const("desktop")])
186
+ .default("both"),
187
+ /**
188
+ * 手机离线时仍由手机侧接管审批/问询的等待上限(毫秒;0 = 关闭,恢复 v3.2.0 的
189
+ * "离线一律交桌面 GUI"行为)。默认 5 分钟。
190
+ *
191
+ * 为什么需要(v3.2.x 跑在 DSH 0.2.x 上的实测缺陷):$events 通道不可用时 approvalMode
192
+ * 降级为 mobile 语义,而手机离线时 answerer 直接 next() 把审批让给桌面;人不在电脑前
193
+ * 时桌面无人应答,内核 approval promise 永久悬挂——会话一直 running、手机端既无卡片
194
+ * 也无待办、连"停止"都因网关签名变化而 400。开启本项后离线也建条目并写回放帧,打开
195
+ * App 时卡片会被补发;超过上限则 fail-close 成 unavailable,让内核继续走。
196
+ */
197
+ offlineHoldMs: z.number().min(0).max(3_600_000).default(300_000),
198
+ /**
199
+ * 手机离线时是否**同时**让桌面 GUI 弹卡(默认 true)。
200
+ * 关掉后回到"离线即由手机独占、桌面不弹";需要在家用桌面审批时保持默认。
201
+ */
202
+ offlineAlsoDesktop: z.boolean().default(true),
203
+ /**
204
+ * 审批/问询推送的宽限期(毫秒,0 = 立即推送)。默认 5000。
205
+ *
206
+ * 审批/问询到达时先挂起这么久再决定要不要推送:期间条目若被结算(桌面先答、另一端
207
+ * 已处理、自动批准),整条通知都不再发出。否则"人就坐在电脑前秒点一下",手机照样
208
+ * 会响一次 —— 纯噪音。与 zen-remote 的同名策略一致(它的默认值也是 5 秒)。
209
+ */
210
+ pushApprovalGraceMs: z.number().min(0).max(60_000).default(5_000),
211
+ });
@@ -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
+ }