dsh-mobile-plugin 0.5.83 → 0.5.85

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/lib/client.js +218 -6
  2. package/lib/http/routing.js +7 -0
  3. package/lib/impl.js +7 -1
  4. package/lib/mobile/channels.js +41 -18
  5. package/lib/mobile/feedback.js +142 -69
  6. package/lib/mobile/forge-contract.js +186 -0
  7. package/lib/mobile/forge-worktree.js +117 -0
  8. package/lib/mobile/forge.js +197 -0
  9. package/lib/mobile/host-bridge/endpoints.js +77 -8
  10. package/lib/mobile/host-bridge/event-synthesis.js +6 -7
  11. package/lib/mobile/host-bridge/shims.js +50 -29
  12. package/lib/mobile/host-settings.js +32 -0
  13. package/lib/mobile/model-caps.js +10 -6
  14. package/lib/mobile/pairing.js +10 -2
  15. package/lib/mobile/permissions.js +32 -0
  16. package/lib/mobile/plugin-market.js +94 -50
  17. package/lib/mobile/plugin-update.js +5 -0
  18. package/lib/mobile/relay-control.js +87 -0
  19. package/lib/mobile/schedule-edit.js +30 -55
  20. package/lib/mobile/schedule.js +98 -24
  21. package/lib/mobile/session-new.js +11 -1
  22. package/lib/mobile/subagents.js +63 -25
  23. package/lib/mobile/worktree-isolation.js +12 -4
  24. package/lib/mobile/worktree-lifecycle.js +2 -0
  25. package/lib/p2p/wiring.cjs +32 -14
  26. package/lib/panel/index.html +22 -21
  27. package/lib/relay/control.js +25 -8
  28. package/lib/relay/core.js +21 -18
  29. package/lib/relay/pairing-payload.cjs +7 -0
  30. package/lib/relay/status.js +2 -1
  31. package/lib/relay/tunnel-forwarder.cjs +5 -3
  32. package/lib/relay/tunnel.js +7 -2
  33. package/lib/remote/host-control.cjs +1 -1
  34. package/lib/routes/control-plane.js +4 -3
  35. package/lib/routes/mobile-api.js +59 -1
  36. package/lib/sidecar-facade-worker.cjs +9 -2
  37. package/lib/sidecar-facade.cjs +50 -22
  38. package/lib/sidecar-lifecycle.cjs +4 -3
  39. package/lib/tailcat/ingress.cjs +5 -3
  40. package/lib/tailcat/wiring.cjs +54 -30
  41. package/package.json +1 -1
@@ -1,51 +1,71 @@
1
+ // 用途:插件反馈的统一提交口——AI 工具与就地入口共用字段、身份与诊断附件,无手机也能提交。
1
2
  'use strict';
2
- // AI 查清问题后直接把反馈提交到分发平台;官方回复在维护者反馈队列跟进,AI 代提的不进 App 反馈列表(2026-11-20)。
3
3
 
4
4
  /**
5
- * 给模型的「反馈」能力:用户在用插件 / App 时遇到问题,AI 先排查;真查出原因后,由 AI
6
- * 直接把反馈提交到分发平台,不用用户自己回 App 里手填。
5
+ * 给模型的「反馈」能力:用户遇到问题时,AI 描述现象、已检查什么、还有哪些不确定,
6
+ * 直接把反馈提交到分发平台;不需要先查明根因,也不需要用户回 App 手填。
7
7
  *
8
8
  * ## 两条途径
9
9
  *
10
- * - **分发平台**:公开反馈接口,与 App 里的反馈页同一个(`/api/sdk/feedback`)。插件把
11
- * 当前连接的设备身份一并带上。官方回复在维护者反馈队列里跟进(`npm run feedback` 查看),
12
- * 这条由 AI 代提的反馈不会出现在 App 的反馈列表里。这条本模块能真的替用户提交。
10
+ * - **分发平台**:公开反馈接口(`/api/sdk/feedback`)。明确指定设备号时带上那台手机的
11
+ * 身份;没指定时用这台电脑上的插件安装身份;没配手机时依然能交,受影响手机那几格留空。
12
+ * 诊断文本作为 text/plain 附件一起发。官方回复在维护者反馈队列里跟进(`npm run feedback`),
13
+ * 这条先留在本机,不会写进 App 的反馈列表,线程 key 当场回显给用户复制。
13
14
  * - **GitHub**:插件代码本身的 bug 可以直接提 PR。这条路依赖用户自己登录 GitHub,
14
15
  * 插件无法代提,所以只把仓库与前提写进说明,由 AI 自己判断走不走。
15
16
  *
16
17
  * ## 身份从哪来
17
18
  *
18
- * 手机的机型 / 平台 / 系统版本 / App 版本 / 包名 / 构建号 / 渠道跟着每条请求的身份头上报,
19
- * 宿主在鉴权通过时写回凭据记录(`lib/shared/device-headers.js` → 凭据库)。这里读最新一条
20
- * 活动记录里的那几格,不另开接口、也不在 App 里输任何东西。
21
- *
22
- * ## 为什么没有附件
23
- *
24
- * 反馈页能带上截图,但 AI 提交的是「查出来的问题与复现」,正文就够;附件要读手机本地文件、
25
- * 走 20MB 上传,是另一条路,这一版不做。
19
+ * 手机身份来自凭据库里每条请求写回的活动记录(机型 / 平台 / 系统版本 / App 版本 / 包名 /
20
+ * 构建号 / 渠道)。未指定设备时用 `instanceId()`——它是落盘在 relay.json 里的 128 位随机
21
+ * 安装 id,不是硬件指纹。这里不读密钥、不读会话内容、不伪造安卓 / iOS / extension 身份。
26
22
  */
27
23
 
24
+ const { randomUUID } = require('node:crypto');
25
+ const { version: COMPONENT_VERSION } = require('../../package.json');
26
+
28
27
  const PLATFORM_ORIGIN = 'https://app.wnluo.com';
29
28
  const FEEDBACK_PATH = '/api/sdk/feedback';
30
29
  const GITHUB_REPO = 'https://github.com/WNLUO/dsh-mobile-plugin';
31
30
 
31
+ /** 新 multipart 字段:提交端恒为插件,产品号固定。 */
32
+ const PRODUCT_SLUG = 'dsh-mobile';
33
+ const SOURCE = 'plugin';
34
+ const COMPONENT_ID = 'dsh-mobile-plugin';
35
+ const ATTACHMENT_NAME = 'diagnosis.txt';
36
+
32
37
  /** 与平台侧对齐的正文上限(App 的反馈页也是这个数)。 */
33
38
  const CONTENT_MAX = 4000;
34
- /** 只有文字、没有附件上传,30 秒足够。 */
39
+ /** 带一份小文本附件,30 秒足够。 */
35
40
  const SUBMIT_TIMEOUT_MS = 30_000;
36
- /**
37
- * 读不到安装包包名时的兜底:与 App 的 `buildPackageName() || PACKAGE_ID` 同一条。
38
- * 插件就是给这个 App 用的,所以这个常量是这台电脑上那份安装包的默认产品号。
39
- */
41
+ /** 明确指定设备、但包名读不到时的兜底;没有设备时这一格留空。 */
40
42
  const DEFAULT_PACKAGE_ID = 'com.dsh.mobile';
41
43
 
42
- /** 两条反馈途径:写进工具说明,也能被 `channels` 动作单独取出来。 */
44
+ /** 同一份内容重试复用同一个 submission_id;键就是内容与线程,不另造哈希。 */
45
+ const submissionIds = new Map();
46
+
47
+ function submissionKeyOf(content, threadKey) {
48
+ return `${content}\n${threadKey || ''}`;
49
+ }
50
+
51
+ /** 同一条反馈重试时沿用第一次的 submission_id。 */
52
+ function submissionIdFor(content, threadKey) {
53
+ const key = submissionKeyOf(content, threadKey);
54
+ if (!submissionIds.has(key)) submissionIds.set(key, randomUUID());
55
+ return submissionIds.get(key);
56
+ }
57
+
58
+ /** 提交成功后清掉:同内容下次提交是新反馈,不能被平台当成重试返回旧线程。 */
59
+ function forgetSubmissionId(content, threadKey) {
60
+ submissionIds.delete(submissionKeyOf(content, threadKey));
61
+ }
62
+
43
63
  function feedbackChannels() {
44
64
  return [
45
65
  {
46
66
  kind: 'distribution',
47
67
  name: 'APP 分发系统反馈',
48
- description: '提交到分发平台的公开反馈接口(与 App 里的反馈页同一个)。插件会自动带上当前连接的设备身份;官方回复在维护者反馈队列里跟进(npm run feedback 查看),这条由 AI 代提的反馈不会出现在 App 的反馈列表里。',
68
+ description: '提交到分发平台的公开反馈接口(与 App 里的反馈页同一个)。没配手机也能提交:指定设备号才带那台手机的身份,否则用这台电脑的插件安装身份;诊断文本作 text/plain 附件。官方回复在维护者反馈队列里跟进(npm run feedback 查看),这条先留在本机,不会写进 App 的反馈列表,提交后当场给出可复制的线程 key。',
49
69
  endpoint: `${PLATFORM_ORIGIN}${FEEDBACK_PATH}`,
50
70
  requiresLogin: false,
51
71
  },
@@ -60,52 +80,85 @@ function feedbackChannels() {
60
80
  }
61
81
 
62
82
  /**
63
- * 选一台设备的身份来提交:给了 `deviceId` 就按它找,没给就用最近连着的那台。
64
- *
65
- * 活动清单本身已按「最近连着」排好序(凭据库的 `activeOut`),所以没指定时取第一台。
66
- * 指定了却找不到,照实报错 —— 不能悄悄换一台,那会把反馈挂到错误的设备上。
83
+ * 只认「明确指定的那台」:给了 deviceId 就按它找,找不到就当没有设备身份可用;
84
+ * 没给时**不默认选最近一台**,交给调用方用提交端安装身份。没有设备不报错。
67
85
  */
68
86
  function pickDevice(devices, deviceId) {
69
87
  const list = Array.isArray(devices) ? devices : [];
70
88
  const wanted = typeof deviceId === 'string' ? deviceId.trim() : '';
71
- if (wanted) {
72
- const found = list.find((device) => device && device.deviceId === wanted);
73
- if (!found) throw new Error(`找不到设备 ${wanted}(可用 \`channels\` 之后按已配对的设备号指定)`);
74
- return found;
75
- }
76
- if (list.length === 0) throw new Error('当前没有已连接的手机,拿不到设备身份,无法提交反馈');
77
- return list[0];
89
+ if (!wanted) return null;
90
+ return list.find((device) => device && device.deviceId === wanted) || null;
91
+ }
92
+
93
+ /** 本地安装身份:relay.json 里落盘的随机实例号,不是硬件指纹。 */
94
+ function localDeviceId(deps) {
95
+ const value = typeof deps && typeof deps.instanceId === 'function' ? deps.instanceId() : '';
96
+ return typeof value === 'string' && value.trim() ? value.trim() : randomUUID();
97
+ }
98
+
99
+ /** 附件里只有插件自己能拿到的诊断字样,不含凭据、密钥或会话内容。 */
100
+ function diagnosisTextOf({ deviceSource, deviceId, submissionId }) {
101
+ return [
102
+ 'dsh-mobile-plugin feedback',
103
+ `source=${SOURCE}`,
104
+ `component_id=${COMPONENT_ID}`,
105
+ `component_version=${COMPONENT_VERSION}`,
106
+ `device_source=${deviceSource}`,
107
+ `device_id=${deviceId}`,
108
+ `submission_id=${submissionId}`,
109
+ ].join('\n');
78
110
  }
79
111
 
80
112
  /**
81
113
  * 拼提交给分发平台的表单。字段名与 App 的反馈页逐字对齐(`app/src/services/feedback.ts`
82
- * 的 `feedbackForm`),这样平台那边看到的是同一种形状。
114
+ * 的 `feedbackForm`),另加插件侧的新字段:`source` / `product_slug` / `component_*` /
115
+ * `submission_id` / `context`,以及一份 text/plain 诊断附件。
83
116
  *
84
- * **不填 `context`**:那是 `{runtime_version, language}`,两样只有 App 自己知道;宿主拿不到,
85
- * 硬编一个只会让平台看到假的运行时。版本相关信息已经由 `version_name` / `build_number` 带着。
117
+ * 没有设备时受影响手机的几格留空,device_id 用本机安装身份,绝不编一个平台或机型出来。
86
118
  */
87
- function buildFeedbackForm(device, content, threadKey) {
119
+ function buildFeedbackForm(device, content, threadKey, options = {}) {
120
+ const opts = options && typeof options === 'object' ? options : {};
121
+ const localId = String(opts.localDeviceId || '');
122
+ const deviceSource = device ? 'paired' : (localId ? 'install' : 'local');
123
+ const deviceId = device ? (device.deviceId || localId) : localId;
124
+ const componentVersion = String(opts.componentVersion || COMPONENT_VERSION);
125
+ const submissionId = String(opts.submissionId || randomUUID());
88
126
  const form = new FormData();
89
- form.append('package_id', device.packageId || DEFAULT_PACKAGE_ID);
90
- form.append('platform', device.platform || '');
91
- form.append('version_name', device.appVersion || '');
92
- form.append('build_number', device.buildNumber || '');
93
- form.append('model', device.model || '');
94
- form.append('system_version', device.osVersion || '');
95
- form.append('channel', device.channel || '');
127
+
128
+ form.append('package_id', device ? (device.packageId || DEFAULT_PACKAGE_ID) : '');
129
+ form.append('platform', device ? (device.platform || '') : '');
130
+ form.append('version_name', device ? (device.appVersion || '') : '');
131
+ form.append('build_number', device ? (device.buildNumber || '') : '');
132
+ form.append('model', device ? (device.model || '') : '');
133
+ form.append('system_version', device ? (device.osVersion || '') : '');
134
+ form.append('channel', device ? (device.channel || '') : '');
135
+ form.append('device_id', deviceId);
96
136
  form.append('content', content);
97
137
  const key = typeof threadKey === 'string' ? threadKey.trim() : '';
98
138
  if (key) form.append('thread_key', key);
99
- form.append('device_id', device.deviceId || '');
139
+
140
+ form.append('product_slug', PRODUCT_SLUG);
141
+ form.append('source', SOURCE);
142
+ form.append('component_id', COMPONENT_ID);
143
+ form.append('component_version', componentVersion);
144
+ form.append('submission_id', submissionId);
145
+ const context = {
146
+ product_slug: PRODUCT_SLUG,
147
+ source: SOURCE,
148
+ component_id: COMPONENT_ID,
149
+ component_version: componentVersion,
150
+ device_source: deviceSource,
151
+ files: opts.diagnosis ? { name: ATTACHMENT_NAME, type: 'text/plain' } : null,
152
+ ...(opts.context && typeof opts.context === 'object' ? opts.context : {}),
153
+ };
154
+ form.append('context', JSON.stringify(context));
155
+ if (opts.diagnosis) {
156
+ form.append('files', new Blob([String(opts.diagnosis)], { type: 'text/plain' }), ATTACHMENT_NAME);
157
+ }
100
158
  return form;
101
159
  }
102
160
 
103
- /**
104
- * 发 multipart 到分发平台。返回平台给的线程对象(含 `thread_key`)。
105
- *
106
- * 网络与状态码的收口与 App 的 `postMultipart` 同口径:2xx 取 `data`,其余尽量读平台回的
107
- * `error` 文案,429 单独说「太频繁」,超时说「超时」。
108
- */
161
+ /** 发 multipart 到分发平台。返回平台给的线程对象(含 `thread_key`)。 */
109
162
  async function postMultipart(form) {
110
163
  const controller = new AbortController();
111
164
  const timer = setTimeout(() => controller.abort(), SUBMIT_TIMEOUT_MS);
@@ -137,26 +190,44 @@ async function postMultipart(form) {
137
190
  }
138
191
 
139
192
  /**
140
- * 真正提交一次:读设备身份 → 拼表单 → 发给平台 → 把线程 key 与一句结论还给 AI。
193
+ * 提交一次:选身份 → 拼表单与诊断附件 → 发给平台 → 把线程 key 与结论还给调用方。
141
194
  *
142
- * `deps` 是装配层给的 `{ credentials, instanceId }`:`instanceId` 是取值器(不是值),
143
- * 与本插件其它「必须传取值器」的地方同一理由 —— 重载后实例号可能变。
195
+ * `options` 可带 `submissionId`(重试时复用)、`diagnosis`(诊断文本)、`context`(诊断摘要)、
196
+ * `componentVersion`(就地入口从宿主读到的版本)。
144
197
  */
145
- async function submitFeedback(deps, content, threadKey, deviceId) {
146
- const devices = deps.credentials.listDevices(deps.instanceId());
198
+ async function submitFeedback(deps, content, threadKey, deviceId, options = {}) {
199
+ const id = typeof deps && typeof deps.instanceId === 'function' ? deps.instanceId() : '';
200
+ const devices = deps && deps.credentials && typeof deps.credentials.listDevices === 'function'
201
+ ? deps.credentials.listDevices(id)
202
+ : [];
147
203
  const device = pickDevice(devices, deviceId);
148
- const form = buildFeedbackForm(device, content, threadKey);
204
+ const localId = localDeviceId(deps);
205
+ const opts = options && typeof options === 'object' ? options : {};
206
+ const submissionId = String(opts.submissionId || submissionIdFor(content, threadKey));
207
+ const deviceSource = device ? 'paired' : (localId ? 'install' : 'local');
208
+ const diagnosis = String(opts.diagnosis || diagnosisTextOf({ deviceSource, deviceId: device ? device.deviceId : localId, submissionId }));
209
+ const form = buildFeedbackForm(device, content, threadKey, {
210
+ localDeviceId: localId,
211
+ submissionId,
212
+ diagnosis,
213
+ componentVersion: opts.componentVersion,
214
+ context: opts.context,
215
+ });
149
216
  const thread = await postMultipart(form);
150
217
  const key = typeof thread.thread_key === 'string' ? thread.thread_key : '';
218
+ // 平台已收下这条:清掉缓存,避免同内容下一次提交被当成重试拿到旧线程。
219
+ // postMultipart 抛错时到不了这里,失败重试仍沿用原来的 submission_id。
220
+ forgetSubmissionId(content, threadKey);
151
221
  return {
152
222
  threadKey: key,
223
+ submissionId,
153
224
  message: key
154
- ? `已提交到分发平台,反馈线程 ${key}。官方回复在维护者反馈队列里跟进(npm run feedback 查看),这条由 AI 代提的反馈不会出现在 App 的反馈列表里。`
225
+ ? `已提交到分发平台,反馈编号 ${key}。请复制编号留档;这条先留在本机,不会写进 App 的反馈列表。`
155
226
  : '已提交到分发平台。',
156
227
  };
157
228
  }
158
229
 
159
- /** 工具注册。`deps` 只给这次装配的凭据库与实例号取值器。 */
230
+ /** 工具注册。`deps` 给这次装配的凭据库与实例号取值器。 */
160
231
  function registerFeedbackTool(ctx, deps) {
161
232
  const { defineTool } = require('@deepseek-ai/dsh-tools');
162
233
  if (!deps || !deps.credentials || typeof deps.instanceId !== 'function') {
@@ -166,9 +237,9 @@ function registerFeedbackTool(ctx, deps) {
166
237
  ctx.tools.register(defineTool({
167
238
  name: 'dsh_feedback',
168
239
  description: 'Report a real problem with this mobile plugin or the AI-HUB app. '
169
- + 'Feedback routes: (1) the APP distribution platform — `submit` sends the content to it, and the plugin fills in the connected device identity automatically; official replies are followed up in the maintainer feedback queue (run `npm run feedback`), and this AI-submitted feedback will not appear in the in-app feedback list. '
240
+ + 'Feedback routes: (1) the APP distribution platform — `submit` sends the content to it. You do NOT need to find the root cause: describe what you observed, what you already checked, and what is still uncertain. No paired phone is required either; without an explicitly chosen device the plugin submits under its local installation identity, with a text/plain diagnostics attachment and a thread key you can show to the user. Official replies are followed up in the maintainer feedback queue (run `npm run feedback`); the feedback stays local first and is not written into the in-app feedback list. '
170
241
  + '(2) GitHub — code-level bugs can go to https://github.com/WNLUO/dsh-mobile-plugin as a pull request or issue, but that needs the user to be logged into GitHub and is not submitted by this tool. '
171
- + 'Use `channels` to list both routes. Only submit after you have actually found the cause: describe the problem, what you checked, and the reproduction or suggested fix.',
242
+ + 'Use `channels` to list both routes.',
172
243
  parameters: {
173
244
  action: {
174
245
  type: 'string',
@@ -178,7 +249,7 @@ function registerFeedbackTool(ctx, deps) {
178
249
  },
179
250
  content: {
180
251
  type: 'string',
181
- description: 'Feedback text for submit: the problem, what you found, and the reproduction or suggested fix. Required for submit (max 4000 chars).',
252
+ description: 'Feedback text for submit: the observed symptom, what you checked, and what remains uncertain. A confirmed root cause is not required. Required for submit (max 4000 chars).',
182
253
  },
183
254
  threadKey: {
184
255
  type: 'string',
@@ -186,7 +257,7 @@ function registerFeedbackTool(ctx, deps) {
186
257
  },
187
258
  deviceId: {
188
259
  type: 'string',
189
- description: 'Optional for submit: which paired device identity to report. Omit to use the most recently connected device.',
260
+ description: 'Optional for submit: a paired device whose identity should be attached. Omit to submit under this plugin installation; a phone is not required.',
190
261
  },
191
262
  },
192
263
  output: {
@@ -235,7 +306,6 @@ function registerFeedbackTool(ctx, deps) {
235
306
  }));
236
307
  }
237
308
 
238
- /** 结果压成一句话,给模型看的那份正文。 */
239
309
  function renderSummary(value) {
240
310
  switch (value.action) {
241
311
  case 'channels': {
@@ -249,12 +319,7 @@ function renderSummary(value) {
249
319
  }
250
320
  }
251
321
 
252
- /**
253
- * 装配层入口:挂 `dsh_feedback` 工具。
254
- *
255
- * 与另外几个工具同一个口径:没有 tools 注入的 profile 只少这个工具,插件其余部分照常装;
256
- * 缺注入时 cordis 抛的是 "without inject"。别的错误照抛,不能把真的注册失败也吞掉。
257
- */
322
+ /** 装配层入口:挂 `dsh_feedback` 工具;没有 tools 注入时只少这个工具。 */
258
323
  function installFeedback(ctx, deps) {
259
324
  try {
260
325
  registerFeedbackTool(ctx, deps);
@@ -265,14 +330,22 @@ function installFeedback(ctx, deps) {
265
330
  }
266
331
 
267
332
  module.exports = {
333
+ ATTACHMENT_NAME,
334
+ COMPONENT_ID,
335
+ COMPONENT_VERSION,
268
336
  DEFAULT_PACKAGE_ID,
269
337
  FEEDBACK_PATH,
270
338
  GITHUB_REPO,
271
339
  PLATFORM_ORIGIN,
340
+ PRODUCT_SLUG,
341
+ SOURCE,
272
342
  buildFeedbackForm,
343
+ diagnosisTextOf,
273
344
  feedbackChannels,
274
345
  installFeedback,
346
+ localDeviceId,
275
347
  pickDevice,
276
348
  registerFeedbackTool,
349
+ submissionIdFor,
277
350
  submitFeedback,
278
351
  };
@@ -0,0 +1,186 @@
1
+ // Forge 移动 API 的固定参数与错误收敛;只允许宿主公开的 Session 绑定动作。
2
+ 'use strict';
3
+
4
+ const COMMIT_RE = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i;
5
+ const MAX_ID = 200;
6
+ const MAX_URL = 2048;
7
+ const MAX_TEXT = 64 * 1024;
8
+ const MAX_PATH = 2048;
9
+ const MAX_REVIEWERS = 50;
10
+ const MAX_REVIEWER_LOGIN = 300;
11
+
12
+ function text(value, max = MAX_TEXT) {
13
+ if (typeof value !== 'string') return '';
14
+ const out = value.trim();
15
+ return out && out.length <= max ? out : out.length > max ? out.slice(0, max) : '';
16
+ }
17
+
18
+ function requiredId(value, name = 'sessionId') {
19
+ const out = text(value, MAX_ID);
20
+ return out ? { value: out } : { error: { code: 'bad-request', message: `需要 ${name}` } };
21
+ }
22
+
23
+ function requiredUrl(value) {
24
+ const out = text(value, MAX_URL);
25
+ if (!out) return { error: { code: 'bad-request', message: '需要变更请求 URL' } };
26
+ return { value: out };
27
+ }
28
+
29
+ function commit(value, name = 'headSha') {
30
+ const out = text(value, 80);
31
+ if (!COMMIT_RE.test(out)) return { error: { code: 'bad-request', message: `${name} 必须是完整提交对象名` } };
32
+ return { value: out.toLowerCase() };
33
+ }
34
+
35
+ function queryString(req, key) {
36
+ try { return new URL(req.url, 'http://x').searchParams.get(key) || ''; } catch { return ''; }
37
+ }
38
+
39
+ function baseBody(body) {
40
+ const session = requiredId(body && body.sessionId);
41
+ if (session.error) return session;
42
+ const url = requiredUrl(body && body.url);
43
+ if (url.error) return url;
44
+ return { value: { sessionId: session.value, url: url.value } };
45
+ }
46
+
47
+ function diffCommits(body) {
48
+ if (body == null || body === null) return { value: null };
49
+ if (typeof body !== 'object' || Array.isArray(body)) return { error: { code: 'bad-request', message: 'commits 必须是 null 或 { from, to }' } };
50
+ const from = commit(body.from, 'commits.from');
51
+ const to = commit(body.to, 'commits.to');
52
+ if (from.error) return from;
53
+ if (to.error) return to;
54
+ return { value: { from: from.value, to: to.value } };
55
+ }
56
+
57
+ function lineComment(value) {
58
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return { error: { code: 'bad-request', message: '评论格式不合法' } };
59
+ const path = text(value.path, MAX_PATH);
60
+ const side = value.side === 'L' || value.side === 'R' ? value.side : '';
61
+ const startLine = value.startLine;
62
+ const endLine = value.endLine;
63
+ const body = typeof value.body === 'string' ? value.body : '';
64
+ if (!path || !side || !Number.isSafeInteger(startLine) || startLine < 1 || !Number.isSafeInteger(endLine) || endLine < startLine || !body.trim() || body.length > MAX_TEXT) {
65
+ return { error: { code: 'bad-request', message: '行评论需要路径、L/R、正整数行号和正文' } };
66
+ }
67
+ return { value: { path, side, startLine, endLine, body } };
68
+ }
69
+
70
+ function reviewRequest(body) {
71
+ const base = baseBody(body);
72
+ if (base.error) return base;
73
+ const request = body && body.request && typeof body.request === 'object' && !Array.isArray(body.request) ? body.request : null;
74
+ if (!request) return { error: { code: 'bad-request', message: '需要 request' } };
75
+ const head = commit(request.headSha);
76
+ if (head.error) return head;
77
+ const kind = request.kind;
78
+ if (kind === 'comment') {
79
+ const comment = lineComment(request.comment);
80
+ if (comment.error) return comment;
81
+ return { value: { ...base.value, request: { headSha: head.value, kind, comment: comment.value } } };
82
+ }
83
+ if (kind !== 'review') return { error: { code: 'bad-request', message: 'request.kind 只能是 comment 或 review' } };
84
+ const event = request.event === 'comment' || request.event === 'approve' || request.event === 'request-changes' ? request.event : '';
85
+ if (!event) return { error: { code: 'bad-request', message: 'review event 不合法' } };
86
+ const reviewBody = typeof request.body === 'string' ? request.body : '';
87
+ const comments = Array.isArray(request.comments) ? request.comments : [];
88
+ if (comments.length > MAX_REVIEWERS) return { error: { code: 'bad-request', message: '评论数量过多' } };
89
+ const normalized = [];
90
+ for (const item of comments) {
91
+ const comment = lineComment(item);
92
+ if (comment.error) return comment;
93
+ normalized.push(comment.value);
94
+ }
95
+ if (event === 'request-changes' && !reviewBody.trim() && normalized.length === 0) {
96
+ return { error: { code: 'bad-request', message: '请求修改必须有正文或行评论' } };
97
+ }
98
+ return { value: { ...base.value, request: { headSha: head.value, kind, event, body: reviewBody, comments: normalized } } };
99
+ }
100
+
101
+ function reviewWrite(body) {
102
+ const base = baseBody(body);
103
+ if (base.error) return base;
104
+ const raw = body.write;
105
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { error: { code: 'bad-request', message: '需要 write' } };
106
+ const head = commit(raw.headSha);
107
+ if (head.error) return head;
108
+ const kind = raw.kind;
109
+ const value = { headSha: head.value, kind };
110
+ if (kind === 'reply') {
111
+ const thread = text(raw.thread, MAX_ID); const bodyText = typeof raw.body === 'string' ? raw.body : '';
112
+ if (!thread || !bodyText.trim() || bodyText.length > MAX_TEXT || typeof raw.pending !== 'boolean') return { error: { code: 'bad-request', message: '回复格式不合法' } };
113
+ value.thread = thread; value.body = bodyText; value.pending = raw.pending;
114
+ } else if (kind === 'resolve') {
115
+ const thread = text(raw.thread, MAX_ID);
116
+ if (!thread || typeof raw.resolved !== 'boolean') return { error: { code: 'bad-request', message: '解决讨论格式不合法' } };
117
+ value.thread = thread; value.resolved = raw.resolved;
118
+ } else if (kind === 'edit-comment') {
119
+ const comment = text(raw.comment, MAX_ID); const bodyText = typeof raw.body === 'string' ? raw.body : '';
120
+ if (!comment || !bodyText.trim() || bodyText.length > MAX_TEXT) return { error: { code: 'bad-request', message: '编辑评论格式不合法' } };
121
+ value.comment = comment; value.body = bodyText;
122
+ } else if (kind === 'delete-comment') {
123
+ const comment = text(raw.comment, MAX_ID); if (!comment) return { error: { code: 'bad-request', message: '需要评论 id' } }; value.comment = comment;
124
+ } else if (kind === 'add-pending') {
125
+ const comment = lineComment(raw.comment); if (comment.error) return comment; value.comment = comment.value;
126
+ } else if (kind === 'submit-pending') {
127
+ const review = text(raw.review, MAX_ID); const event = raw.event === 'comment' || raw.event === 'approve' || raw.event === 'request-changes' ? raw.event : '';
128
+ const bodyText = typeof raw.body === 'string' ? raw.body : '';
129
+ if (!review || !event || (event === 'request-changes' && !bodyText.trim())) return { error: { code: 'bad-request', message: '提交待审评审格式不合法' } };
130
+ value.review = review; value.event = event; value.body = bodyText;
131
+ } else if (kind === 'discard-pending') {
132
+ const review = text(raw.review, MAX_ID); if (!review) return { error: { code: 'bad-request', message: '需要待审评审 id' } }; value.review = review;
133
+ } else return { error: { code: 'bad-request', message: '不支持的 review write 类型' } };
134
+ return { value: { ...base.value, write: value } };
135
+ }
136
+
137
+ function reviewers(body) {
138
+ const base = baseBody(body); if (base.error) return base;
139
+ if (!Array.isArray(body.reviewers) || body.reviewers.length === 0 || body.reviewers.length > MAX_REVIEWERS) return { error: { code: 'bad-request', message: '需要非空 reviewers' } };
140
+ const list = [];
141
+ for (const row of body.reviewers) {
142
+ if (!row || (row.kind !== 'user' && row.kind !== 'bot' && row.kind !== 'team')) return { error: { code: 'bad-request', message: 'reviewer kind 不合法' } };
143
+ const login = text(row.login, MAX_REVIEWER_LOGIN); if (!login) return { error: { code: 'bad-request', message: 'reviewer login 不能为空' } };
144
+ list.push({ kind: row.kind, login });
145
+ }
146
+ return { value: { ...base.value, reviewers: list } };
147
+ }
148
+
149
+ function errorResponse(error) {
150
+ const raw = error || {};
151
+ const hostCode = typeof raw.code === 'string' ? raw.code : 'forge-failed';
152
+ const message = typeof raw.message === 'string' && raw.message ? raw.message : String(raw);
153
+ const map = {
154
+ 'bad-request': ['bad-request', 400],
155
+ 'forge-timeout': ['forge-timeout', 504],
156
+ 'unauthenticated': ['forge-unauthenticated', 401],
157
+ 'unsupported': ['forge-unsupported', 501],
158
+ 'too-large': ['forge-too-large', 413],
159
+ 'stale': ['forge-stale', 409],
160
+ 'unknown': ['forge-unknown', 409],
161
+ 'not-found': ['forge-not-found', 404],
162
+ 'unavailable': ['forge-unavailable', 503],
163
+ 'host-unavailable': ['forge-unavailable', 503],
164
+ 'forgePanel/not-bound': ['forge-not-bound', 404],
165
+ 'forgePanel/stale-head': ['forge-stale', 409],
166
+ 'forgePanel/action-unknown': ['forge-unknown', 409],
167
+ 'forgePanel/action-failed': ['forge-action-failed', 502],
168
+ 'forgePanel/diff-too-large': ['forge-too-large', 413],
169
+ 'forgePanel/diff-failed': ['forge-diff-failed', 502],
170
+ 'forgePanel/checks-failed': ['forge-checks-failed', 502],
171
+ 'forgePanel/review-unsupported': ['forge-review-unsupported', 501],
172
+ 'forgePanel/review-failed': ['forge-review-failed', 502],
173
+ 'forgePanel/viewed-failed': ['forge-viewed-failed', 502],
174
+ 'forgePanel/reviewers-failed': ['forge-reviewers-failed', 502],
175
+ 'forgePanel/worktrees-unavailable': ['worktree-unavailable', 503],
176
+ 'forgePanel/session-started': ['worktree-session-started', 409],
177
+ 'forgePanel/session-busy': ['worktree-session-busy', 409],
178
+ 'forgePanel/no-worktree': ['worktree-missing', 404],
179
+ 'forgePanel/not-waiting': ['worktree-not-waiting', 409],
180
+ 'forgePanel/restore-failed': ['worktree-restore-failed', 502],
181
+ };
182
+ const [code, status] = map[hostCode] || ['forge-failed', 502];
183
+ return { status, error: { code, message, details: { hostCode } } };
184
+ }
185
+
186
+ module.exports = { MAX_ID, MAX_URL, COMMIT_RE, text, requiredId, requiredUrl, commit, queryString, baseBody, diffCommits, lineComment, reviewRequest, reviewWrite, reviewers, errorResponse };
@@ -0,0 +1,117 @@
1
+ // 官方 Forge 面板与工作树生命周期;Session 权限、首消息等待和归档回收均由宿主拥有。
2
+ 'use strict';
3
+
4
+ const { sendJson, readJsonBody } = require('../shared/http-util');
5
+ const { requestSignal } = require('../shared/fresh-request.js');
6
+ const { invoke, openStream } = require('./host-bridge/transport.js');
7
+ const { requiredId, text, queryString, errorResponse } = require('./forge-contract.js');
8
+
9
+ const STATE_DEADLINE_MS = 15000;
10
+ const WORKTREE_ACTIONS = Object.freeze({
11
+ request: 'requestWorktree', cancel: 'cancelWorktree', stop: 'stopCreation',
12
+ retry: 'retryWorktree', restore: 'restoreWorktree', continue: 'continueInProject',
13
+ });
14
+
15
+ function serviceOf(ctx, name) {
16
+ try { return typeof ctx?.get === 'function' ? ctx.get(name) || null : null; } catch { return null; }
17
+ }
18
+
19
+ function capabilitiesOf(ctx) {
20
+ const panel = serviceOf(ctx, 'forgePanel');
21
+ const gateway = serviceOf(ctx, 'typertGateway');
22
+ const available = !!panel && !!gateway && typeof gateway.invoke === 'function' && typeof gateway.stream === 'function';
23
+ const worktrees = serviceOf(ctx, 'worktrees');
24
+ const worktree = {
25
+ available: available && !!worktrees,
26
+ create: available && typeof panel?.requestWorktree === 'function' && typeof worktrees?.create === 'function',
27
+ restore: available && typeof panel?.restoreWorktree === 'function' && typeof worktrees?.restore === 'function',
28
+ archiveCleanup: available && typeof panel?.worktreeCleanup === 'function' && typeof worktrees?.cleanupOf === 'function',
29
+ owner: available && worktrees ? 'host' : 'unavailable',
30
+ };
31
+ return { available, ...(available ? {} : { reason: '宿主没有挂载 Forge 面板服务' }), worktree };
32
+ }
33
+
34
+ function unavailable(message = '宿主没有挂载 Forge 面板服务') { return Object.assign(new Error(message), { code: 'host-unavailable' }); }
35
+
36
+ async function callPanel(ctx, method, args, signal) {
37
+ if (!capabilitiesOf(ctx).available) throw unavailable();
38
+ const result = await invoke(ctx, 'forgePanel', method, args, signal);
39
+ if (result.error) throw Object.assign(new Error(result.error.message), result.error);
40
+ return result.value;
41
+ }
42
+
43
+ async function readPanelState(ctx, sessionId, signal, options = {}) {
44
+ if (!capabilitiesOf(ctx).available) throw unavailable();
45
+ const controller = new AbortController();
46
+ const timeout = setTimeout(() => controller.abort(Object.assign(new Error('Forge 状态读取超时'), { code: 'forge-timeout' })), STATE_DEADLINE_MS);
47
+ const abort = () => controller.abort(signal?.reason);
48
+ signal?.addEventListener('abort', abort, { once: true });
49
+ if (signal?.aborted) abort();
50
+ let latest = null;
51
+ try {
52
+ const stream = await openStream(ctx, 'forgePanel', 'follow', { sessionId }, controller.signal);
53
+ for await (const state of stream) {
54
+ if (!state || typeof state !== 'object' || !state.worktree) continue;
55
+ latest = state;
56
+ if (state.checkout?.state === 'pending') continue;
57
+ if (options.url) {
58
+ const entry = Array.isArray(state.changeRequests) ? state.changeRequests.find(item => item?.url === options.url) : null;
59
+ if (!entry) throw Object.assign(new Error('变更请求没有绑定到此会话'), { code: 'forgePanel/not-bound' });
60
+ }
61
+ return state;
62
+ }
63
+ if (latest) return latest;
64
+ throw controller.signal.reason || unavailable('宿主没有返回 Forge 面板状态');
65
+ } finally {
66
+ clearTimeout(timeout); controller.abort(); signal?.removeEventListener('abort', abort);
67
+ }
68
+ }
69
+
70
+ async function requestForNew(ctx, sessionId, options = {}, signal) {
71
+ if (options.keep === true) throw Object.assign(new Error('官方工作树没有逐棵保留策略;请在电脑上设置归档保留后再创建'), { code: 'worktree-keep-unsupported' });
72
+ if (!capabilitiesOf(ctx).worktree.create) throw unavailable('宿主没有挂载官方工作树创建服务');
73
+ const from = options.from == null ? null : text(options.from, 300);
74
+ if (from === '') throw Object.assign(new Error('基准分支不能为空'), { code: 'bad-request' });
75
+ await callPanel(ctx, 'requestWorktree', { sessionId, from }, signal);
76
+ return { worktreeRequested: true, worktreeOwner: 'host' };
77
+ }
78
+
79
+ function sendError(res, error) {
80
+ if (error?.code === 'bad-request' || error?.code === 'worktree-keep-unsupported') return sendJson(res, 400, { ok: false, error: { code: error.code, message: error.message } });
81
+ const result = errorResponse(error); sendJson(res, result.status, { ok: false, error: result.error });
82
+ }
83
+ function sendValue(res, value) {
84
+ if (value === undefined) return sendJson(res, 200, { ok: true, applied: true });
85
+ if (value === null) return sendJson(res, 200, { ok: true, supported: false });
86
+ sendJson(res, 200, { ok: true, ...value });
87
+ }
88
+
89
+ async function handleForgeCapabilities(ctx, _req, res) { sendJson(res, 200, { ok: true, ...capabilitiesOf(ctx) }); }
90
+ async function handleForgeState(ctx, req, res) {
91
+ const session = requiredId(queryString(req, 'sessionId')); if (session.error) return sendJson(res, 400, { ok: false, error: session.error });
92
+ try { sendValue(res, await readPanelState(ctx, session.value, requestSignal(res))); } catch (error) { sendError(res, error); }
93
+ }
94
+ async function handleWorktreeState(ctx, req, res) {
95
+ const session = requiredId(queryString(req, 'sessionId')); if (session.error) return sendJson(res, 400, { ok: false, error: session.error });
96
+ try { const state = await readPanelState(ctx, session.value, requestSignal(res)); sendJson(res, 200, { ok: true, worktree: state.worktree, capabilities: capabilitiesOf(ctx).worktree }); } catch (error) { sendError(res, error); }
97
+ }
98
+ async function handleWorktreeCleanup(ctx, req, res) {
99
+ const session = requiredId(queryString(req, 'sessionId')); if (session.error) return sendJson(res, 400, { ok: false, error: session.error });
100
+ const raw = queryString(req, 'revision'); const revision = raw === '' ? null : Number(raw);
101
+ if (revision !== null && (!Number.isSafeInteger(revision) || revision < 0)) return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: 'revision 必须是非负整数' } });
102
+ try { sendJson(res, 200, { ok: true, cleanup: await callPanel(ctx, 'worktreeCleanup', { sessionId: session.value, revision }, requestSignal(res)) }); } catch (error) { sendError(res, error); }
103
+ }
104
+ async function applyWorktree(ctx, req, res, action) {
105
+ const body = await readJsonBody(req, 16 * 1024) || {}; const session = requiredId(body.sessionId);
106
+ if (session.error) return sendJson(res, 400, { ok: false, error: session.error });
107
+ const args = { sessionId: session.value };
108
+ if (action === 'request') { if (body.keep === true || body.keepWorktree === true) return sendError(res, { code: 'worktree-keep-unsupported', message: '官方工作树没有逐棵保留策略' }); args.from = body.from == null ? null : text(body.from, 300); if (args.from === '') return sendError(res, { code: 'bad-request', message: '基准分支不能为空' }); }
109
+ try { await callPanel(ctx, WORKTREE_ACTIONS[action], args, requestSignal(res)); sendJson(res, 200, { ok: true, applied: true }); } catch (error) { sendError(res, error); }
110
+ }
111
+ async function handleWorktreeRequest(ctx, req, res) { return applyWorktree(ctx, req, res, 'request'); }
112
+ async function handleWorktreeCancel(ctx, req, res) { return applyWorktree(ctx, req, res, 'cancel'); }
113
+ async function handleWorktreeStop(ctx, req, res) { return applyWorktree(ctx, req, res, 'stop'); }
114
+ async function handleWorktreeRetry(ctx, req, res) { return applyWorktree(ctx, req, res, 'retry'); }
115
+ async function handleWorktreeRestore(ctx, req, res) { return applyWorktree(ctx, req, res, 'restore'); }
116
+ async function handleWorktreeContinue(ctx, req, res) { return applyWorktree(ctx, req, res, 'continue'); }
117
+ module.exports = { capabilitiesOf, callPanel, readPanelState, requestForNew, sendError, handleForgeCapabilities, handleForgeState, handleWorktreeState, handleWorktreeCleanup, handleWorktreeRequest, handleWorktreeCancel, handleWorktreeStop, handleWorktreeRetry, handleWorktreeRestore, handleWorktreeContinue };