dsh-mobile-plugin 0.5.33 → 0.5.35

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 (142) hide show
  1. package/README.md +17 -2
  2. package/dsh-mobile-credentials/lib/credentials.js +49 -2
  3. package/extensions/README.md +25 -21
  4. package/host.js +16 -1
  5. package/lib/git/pr.js +375 -0
  6. package/lib/git/read.js +1 -0
  7. package/lib/host-capabilities.cjs +67 -0
  8. package/lib/http/routing.js +25 -0
  9. package/lib/impl.js +34 -26
  10. package/lib/mirror/history-blob.cjs +184 -0
  11. package/lib/mirror/pusher.cjs +276 -1
  12. package/lib/mobile/approval-facts.js +439 -0
  13. package/lib/mobile/approval-memory.js +199 -0
  14. package/lib/mobile/approvals.js +596 -30
  15. package/lib/mobile/auto-review-log.js +160 -0
  16. package/lib/mobile/auto-review.js +172 -0
  17. package/lib/mobile/credential-upgrade.js +14 -0
  18. package/lib/mobile/device-permissions.js +86 -0
  19. package/lib/mobile/directory-browse.js +23 -8
  20. package/lib/mobile/events.js +9 -1
  21. package/lib/mobile/extension-catalog.js +106 -44
  22. package/lib/mobile/extension-data.js +6 -0
  23. package/lib/mobile/file-ops.js +89 -76
  24. package/lib/mobile/git.js +108 -2
  25. package/lib/mobile/live-steps.js +107 -4
  26. package/lib/mobile/mail.js +621 -0
  27. package/lib/mobile/monitor.js +6 -0
  28. package/lib/mobile/notification-prefs.js +205 -0
  29. package/lib/mobile/pairing.js +15 -2
  30. package/lib/mobile/permissions.js +433 -0
  31. package/lib/mobile/project-write-queue.js +115 -0
  32. package/lib/mobile/project-writes.js +61 -0
  33. package/lib/mobile/push-notify.js +293 -13
  34. package/lib/mobile/questions.js +20 -3
  35. package/lib/mobile/recent-failures.js +48 -0
  36. package/lib/mobile/relay-control.js +5 -0
  37. package/lib/mobile/session-cache.js +50 -0
  38. package/lib/mobile/session-last-turn.js +24 -22
  39. package/lib/mobile/session-new.js +205 -0
  40. package/lib/mobile/session-send.js +0 -1
  41. package/lib/mobile/sessions.js +12 -84
  42. package/lib/mobile/skill-write.js +549 -0
  43. package/lib/mobile/stats-collect.cjs +33 -3
  44. package/lib/mobile/stats-ledger.cjs +39 -2
  45. package/lib/mobile/stream.js +24 -3
  46. package/lib/mobile/supervisor-broadcast.js +58 -11
  47. package/lib/mobile/supervisor-tools.js +1 -1
  48. package/lib/mobile/third-party-extensions.js +158 -0
  49. package/lib/mobile/uploads.js +30 -14
  50. package/lib/mobile/worktree-isolation.js +479 -0
  51. package/lib/mobile/worktree-lifecycle.js +79 -0
  52. package/lib/p2p/wiring.cjs +41 -16
  53. package/lib/panel/index.html +15 -15
  54. package/lib/read-receipt.cjs +89 -5
  55. package/lib/relay/core.js +25 -1
  56. package/lib/relay/lan-proxy.js +6 -1
  57. package/lib/relay/preview.js +21 -1
  58. package/lib/relay/protocol.js +1 -0
  59. package/lib/relay/status.js +6 -0
  60. package/lib/relay/tunnel-forwarder.cjs +178 -0
  61. package/lib/routes/control-plane.js +35 -1
  62. package/lib/routes/mobile-api.js +105 -52
  63. package/lib/shared/via-header.js +15 -2
  64. package/lib/sidecar-facade-worker.cjs +15 -2
  65. package/lib/sidecar-facade.cjs +5 -0
  66. package/lib/tailcat/host-process.cjs +1 -1
  67. package/lib/tailcat/ingress.cjs +2 -2
  68. package/lib/tailcat/wiring.cjs +34 -13
  69. package/package.json +11 -3
  70. package/assets/pets/README.md +0 -9
  71. package/assets/pets/deepy-whale/attention.gif +0 -0
  72. package/assets/pets/deepy-whale/done.gif +0 -0
  73. package/assets/pets/deepy-whale/error.gif +0 -0
  74. package/assets/pets/deepy-whale/idle.gif +0 -0
  75. package/assets/pets/deepy-whale/pack.json +0 -54
  76. package/assets/pets/deepy-whale/sleeping.gif +0 -0
  77. package/assets/pets/deepy-whale/working-3.gif +0 -0
  78. package/assets/pets/deepy-whale/working.gif +0 -0
  79. package/knowledge/apps/alipay.md +0 -30
  80. package/knowledge/apps/android-settings.md +0 -30
  81. package/knowledge/apps/baijiahao.md +0 -30
  82. package/knowledge/apps/bilibili.md +0 -31
  83. package/knowledge/apps/boss-zhipin.md +0 -32
  84. package/knowledge/apps/dedao.md +0 -33
  85. package/knowledge/apps/douyin.md +0 -32
  86. package/knowledge/apps/feishu.md +0 -35
  87. package/knowledge/apps/gmail.md +0 -33
  88. package/knowledge/apps/jike.md +0 -31
  89. package/knowledge/apps/kuaishou.md +0 -34
  90. package/knowledge/apps/linkedin.md +0 -33
  91. package/knowledge/apps/qqmail.md +0 -30
  92. package/knowledge/apps/taobao.md +0 -33
  93. package/knowledge/apps/telegram.md +0 -27
  94. package/knowledge/apps/toutiao.md +0 -32
  95. package/knowledge/apps/uber-eats.md +0 -26
  96. package/knowledge/apps/uber.md +0 -27
  97. package/knowledge/apps/wechat.md +0 -33
  98. package/knowledge/apps/weibo.md +0 -31
  99. package/knowledge/apps/whatsapp.md +0 -27
  100. package/knowledge/apps/x.md +0 -32
  101. package/knowledge/apps/xiaohongshu.md +0 -30
  102. package/knowledge/apps/zhihu.md +0 -31
  103. package/knowledge/sites/bilibili.com/SITE.md +0 -50
  104. package/knowledge/sites/bilibili.com/references/view-fields.md +0 -17
  105. package/knowledge/sites/github.com/SITE.md +0 -51
  106. package/knowledge/sites/github.com/references/repo-fields.md +0 -13
  107. package/knowledge/sites/x.com/SITE.md +0 -47
  108. package/knowledge/sites/xiaohongshu.com/SITE.md +0 -48
  109. package/knowledge/sites/xiaohongshu.com/references/note-fields.md +0 -18
  110. package/knowledge/sites/youtube.com/SITE.md +0 -49
  111. package/knowledge/sites/youtube.com/references/innertube-fields.md +0 -14
  112. package/knowledge/sites/zhihu.com/SITE.md +0 -47
  113. package/knowledge/sites/zhihu.com/references/api-fields.md +0 -21
  114. package/lib/mobile/pet-tools.js +0 -261
  115. package/lib/mobile/pets.js +0 -755
  116. package/lib/mobile/phone/access.js +0 -85
  117. package/lib/mobile/phone/binding.js +0 -247
  118. package/lib/mobile/phone/confirm.js +0 -189
  119. package/lib/mobile/phone/evidence.js +0 -228
  120. package/lib/mobile/phone/gate.js +0 -290
  121. package/lib/mobile/phone/grounding.js +0 -314
  122. package/lib/mobile/phone/guard.js +0 -465
  123. package/lib/mobile/phone/index.js +0 -83
  124. package/lib/mobile/phone/irreversible.js +0 -226
  125. package/lib/mobile/phone/knowledge-tools.js +0 -665
  126. package/lib/mobile/phone/learn.js +0 -329
  127. package/lib/mobile/phone/pacing.js +0 -173
  128. package/lib/mobile/phone/redact.js +0 -237
  129. package/lib/mobile/phone/risk.js +0 -95
  130. package/lib/mobile/phone/route-hint.js +0 -164
  131. package/lib/mobile/phone/routes-memory.js +0 -133
  132. package/lib/mobile/phone/routes.js +0 -279
  133. package/lib/mobile/phone/service.js +0 -500
  134. package/lib/mobile/phone/site-commands.js +0 -271
  135. package/lib/mobile/phone/step-summary.js +0 -201
  136. package/lib/mobile/phone/stop-summary.js +0 -235
  137. package/lib/mobile/phone/tool-groups.js +0 -125
  138. package/lib/mobile/phone/tools.js +0 -2282
  139. package/lib/mobile/phone/untrusted.js +0 -65
  140. package/lib/mobile/phone-knowledge.js +0 -317
  141. package/lib/mobile/wechat-tools.js +0 -257
  142. package/lib/mobile/wechat.js +0 -514
@@ -0,0 +1,205 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * `POST /session/new`:新建空白会话,以及 `isolate: true` 那条隔离工作目录的路。
5
+ *
6
+ * 为什么单列一个文件:`sessions.js` 有 500 行的拆分上限(见 `test/module-split.test.cjs`),
7
+ * 而新建会话这一段是它身上唯一还在长的部分 —— 隔离那条路要开工作树、要回滚、要登记,
8
+ * 再往列表 handler 里塞就把那个文件顶爆了。`sessions.js` 继续转出 `handleNew`,所以
9
+ * 路由表与测试的 import 路径一行都不用改。
10
+ *
11
+ * ## 隔离是一条**事务**(2026-11-10 修)
12
+ *
13
+ * 建树与建会话此前是两件互不相干的事:树建好了、`session.create` 随即失败,那棵树就成了
14
+ * 孤儿 —— 没有会话指向它,也没有任何登记说它存在,只有手工 `git worktree prune` 能收。
15
+ * 现在两条路都堵上:失败时立刻回收刚建的那棵;同一个 requestId 重投时复用已经建好的那棵
16
+ * (幂等窗口对 5xx 会删记录,重投会真的再进来一遍)。
17
+ *
18
+ * ## 能力面
19
+ *
20
+ * `isolate: true` 是唯一一条不走「cwd 必须在已登记工作区里」的路,但它**不是**放开任意
21
+ * 路径:App 只发一个布尔,目录由插件在项目仓库里自己开一棵 git worktree。所以能力面仍然
22
+ * 停在「已登记工作区」这一层。
23
+ */
24
+
25
+ const path = require('node:path');
26
+
27
+ const { sendJson, readJsonBody } = require('../shared/http-util');
28
+ const { workspaceRoots, isWithin } = require('./allowed-zone.js');
29
+ const { withIdempotency, requestIdOf } = require('./idempotency.js');
30
+ const { canonicalDeviceKey, invalidateSessionList } = require('./session-cache.js');
31
+ const { unwrap } = require('./envelope.js');
32
+ const { callSessions } = require('./rpc.js');
33
+ const {
34
+ createIsolationWorktreeForNew, releaseIsolationWorktree, bindSession,
35
+ } = require('./worktree-isolation.js');
36
+
37
+ /**
38
+ * 会话没建成时收掉这一次刚开的树:目录、git 里的登记,以及那条还没干过活的分支。
39
+ *
40
+ * 分支上有提交就留着(那是用户在树里干完的活),判断在 `releaseIsolationWorktree` 里。
41
+ * 清理失败不抛 —— 原始失败才是要报给用户的那一个。
42
+ */
43
+ async function discardIsolated(isolated) {
44
+ if (!isolated) return;
45
+ await releaseIsolationWorktree({
46
+ repoRoot: isolated.repoRoot,
47
+ cwd: isolated.cwd,
48
+ branch: isolated.branch,
49
+ baseSha: isolated.baseSha,
50
+ });
51
+ }
52
+
53
+ /**
54
+ * POST /api/mobile/v1/session/new(token){ workspaceId? | cwd? | isolate? | keepWorktree? }
55
+ * → { ok, sessionId, cwd }
56
+ *
57
+ * 优先 workspaceId:宿主把新会话 attach 到该项目(workspace)的 sessionIds 账上,桌面端
58
+ * 侧栏项目下立即可见;无 workspaceId 时回退 cwd(不传则归属其默认/未分组工作区)。
59
+ * `isolate: true` 时改由插件在项目仓库里开一棵 git worktree 并把会话 cwd 指过去;
60
+ * `keepWorktree: true` 表示这棵树建好后**不自动回收**(默认在会话结束后清掉)。
61
+ * 走宿主 apiProxy 的 session.create(接受 workspaceId 或 cwd,二者不能同时给)。
62
+ *
63
+ * cwd 进来之前必须落在**宿主已登记的工作区**里:会话的 cwd 就是 allowed-zone 的第二个
64
+ * 根(见 allowed-zone.js 的 allowedRoots),随手塞一个 `/` 进来等于把整台机器变成
65
+ * 「允许读写区」。工作区清单读不到时照实回 502,不按「没有工作区」处理 —— 那会让每个
66
+ * 目录都变成 403,用户看到的是「我的目录突然不能用了」。
67
+ */
68
+ async function handleNew(ctx, req, res) {
69
+ const body = await readJsonBody(req, 64 * 1024);
70
+ const workspaceId = body && typeof body.workspaceId === 'string' && body.workspaceId.trim()
71
+ ? body.workspaceId.trim()
72
+ : '';
73
+ const isolate = !!(body && body.isolate === true);
74
+ const keepWorktree = !!(body && body.keepWorktree === true);
75
+ // 隔离那条路要一个可解析的项目落点:优先 workspaceId,其次调用方给的 cwd。
76
+ let projectCwd = '';
77
+ // 只有走 cwd 那条路才需要校验:workspaceId 本身就把范围交给了宿主登记过的那一项。
78
+ let cwd = '';
79
+ if (!workspaceId && body && typeof body.cwd === 'string' && body.cwd.trim()) {
80
+ const declared = body.cwd.trim();
81
+ if (!path.isAbsolute(declared)) {
82
+ return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: 'cwd 必须是绝对路径' } });
83
+ }
84
+ cwd = path.resolve(declared);
85
+ let roots;
86
+ try {
87
+ roots = await workspaceRoots(ctx);
88
+ } catch (error) {
89
+ return sendJson(res, 502, {
90
+ ok: false,
91
+ error: {
92
+ code: (error && error.code) || 'workspace-list-failed',
93
+ message: String((error && error.message) || error),
94
+ },
95
+ });
96
+ }
97
+ if (!roots.some((root) => isWithin(root, cwd))) {
98
+ return sendJson(res, 403, {
99
+ ok: false,
100
+ error: { code: 'outside-allowed', message: '这个目录不在能建会话的范围里(只能落在已登记的工作区)' },
101
+ });
102
+ }
103
+ }
104
+ if (isolate) {
105
+ projectCwd = cwd;
106
+ if (!workspaceId && !projectCwd) {
107
+ return sendJson(res, 400, {
108
+ ok: false,
109
+ error: { code: 'bad-request', message: '开隔离工作目录需要指定一个项目' },
110
+ });
111
+ }
112
+ }
113
+ // 新建会话是**非幂等**写:同一发请求被重投一次就会凭空多一个会话。requestId 由
114
+ // App 在构造请求头时生成一次,内核换通道重投复用同一个 init(同一个头),重投于是
115
+ // 命中这里、直接拿回第一次的 sessionId(见 mobile/idempotency.js)。
116
+ const requestId = requestIdOf(req, body);
117
+ const outcome = await withIdempotency(ctx, canonicalDeviceKey(req), requestId, async () => {
118
+ let payload = {};
119
+ // 这一次请求建的那棵树:create 失败时按它回滚。
120
+ let isolated = null;
121
+ if (isolate) {
122
+ // 建树失败就整次失败:不退回「就在原目录建会话」,否则用户以为已经隔离了、实际还在
123
+ // 跟别人抢同一批文件。
124
+ try {
125
+ isolated = await createIsolationWorktreeForNew(ctx, {
126
+ workspaceId: workspaceId || undefined,
127
+ cwd: projectCwd || undefined,
128
+ label: workspaceId || projectCwd,
129
+ // 同一个 requestId 重投时复用它建过的那棵,而不是再开一棵。
130
+ reuseKey: requestId || undefined,
131
+ keep: keepWorktree,
132
+ });
133
+ } catch (error) {
134
+ return {
135
+ status: error && error.code === 'not-a-git-repo' ? 400 : 502,
136
+ body: {
137
+ ok: false,
138
+ error: {
139
+ code: (error && error.code) || 'worktree-failed',
140
+ message: String((error && error.message) || error),
141
+ },
142
+ },
143
+ };
144
+ }
145
+ payload.cwd = isolated.cwd;
146
+ } else if (workspaceId) {
147
+ payload.workspaceId = workspaceId;
148
+ } else if (cwd) {
149
+ payload.cwd = cwd;
150
+ }
151
+ // 宿主 session.create 接受 agentPreset:新建时直接定档,省掉「先建再 select」的
152
+ // 两步(select 只在会话还没开跑时生效,新建后立刻 select 同样可行但多一次 RPC)。
153
+ if (body && typeof body.agentPreset === 'string' && body.agentPreset.trim()) {
154
+ payload.agentPreset = body.agentPreset.trim();
155
+ }
156
+ let create;
157
+ try {
158
+ create = unwrap(await callSessions(ctx, 'create', payload));
159
+ } catch (error) {
160
+ // 宿主那层直接抛了(网关不可用之类):这棵树同样没人要了,收掉再说失败。
161
+ await discardIsolated(isolated);
162
+ throw error;
163
+ }
164
+ const { value, error } = create;
165
+ if (error) {
166
+ // 树已经建好、会话没建成:**回滚那棵树**。留着就是一具没人认领的孤儿,
167
+ // 会话列表里不会出现、登记表里也没人会来收。
168
+ await discardIsolated(isolated);
169
+ return { status: 400, body: { ok: false, error } };
170
+ }
171
+ const sessionId = value && typeof value.sessionId === 'string' ? value.sessionId : null;
172
+ if (!sessionId) {
173
+ await discardIsolated(isolated);
174
+ return { status: 500, body: { ok: false, error: { code: 'internal', message: '新建会话未返回 sessionId' } } };
175
+ }
176
+ // 树归这条会话了:登记表把「建树时那个请求键」改挂到会话号上,之后会话结束
177
+ // (归档 / 删除)时 `worktree-lifecycle.js` 才能按会话号找到它并收掉。
178
+ // 分支名与基线一起带过去 —— 回收时靠它判断分支上有没有用户留下的提交。
179
+ if (isolated) {
180
+ bindSession(sessionId, {
181
+ cwd: isolated.cwd,
182
+ repoRoot: isolated.repoRoot,
183
+ reuseKey: requestId || undefined,
184
+ keep: keepWorktree,
185
+ branch: isolated.branch,
186
+ baseSha: isolated.baseSha,
187
+ });
188
+ }
189
+ // 新建的会话要立刻出现在列表里,否则手机端最长 10 秒看不到它。
190
+ invalidateSessionList(ctx);
191
+ return {
192
+ status: 200,
193
+ body: {
194
+ ok: true,
195
+ sessionId,
196
+ cwd: payload.cwd || null,
197
+ ...(isolated ? { isolated: true, keepWorktree: keepWorktree || undefined } : {}),
198
+ ...(value && typeof value.agentPreset === 'string' ? { agentPreset: value.agentPreset } : {}),
199
+ },
200
+ };
201
+ });
202
+ sendJson(res, outcome.status, outcome.body);
203
+ }
204
+
205
+ module.exports = { handleNew };
@@ -170,7 +170,6 @@ async function handleSend(ctx, req, res) {
170
170
  if (normalized.code === MODEL_UNAVAILABLE_ERROR.code) invalidateSessionModels(ctx, req, body.sessionId);
171
171
  return sendJson(res, 400, { ok: false, error: continuation ? continuationError(normalized) : normalized });
172
172
  }
173
- require('./phone/binding.js').noteRequestSender(req, body.sessionId);
174
173
  sendJson(res, 200, { ok: true, accepted: true });
175
174
  }
176
175
 
@@ -14,18 +14,14 @@
14
14
  * 所以 lib/mobile 下的 import 路径一行都不用改。
15
15
  */
16
16
 
17
- const path = require('node:path');
18
-
19
17
  const { sendJson, readJsonBody } = require('../shared/http-util');
20
18
  const { isFreshRequest } = require('../shared/fresh-request');
21
19
  const { listRevision, unchangedListBody } = require('../shared/list-revision.js');
22
20
  const { listSignal: sharedListSignal } = require('../shared/list-signal.js');
23
21
  const { listShortcut, rememberListBuild } = require('./session-list-shortcut.js');
24
- const { withIdempotency, requestIdOf } = require('./idempotency.js');
25
22
  const { listTitle, deriveMessages, lastMessageOf, promptErrorObject, MODEL_UNAVAILABLE_ERROR } = require('./history-derive.js');
26
23
  const { unwrap } = require('./envelope.js');
27
24
  const { callSessions } = require('./rpc.js');
28
- const { workspaceRoots, isWithin } = require('./allowed-zone.js');
29
25
  const {
30
26
  canonicalDeviceKey, sessionListResponseState, invalidateSessionList, deletedSessionIdsOf,
31
27
  completionGenerationOf, bumpCompletionGeneration,
@@ -50,6 +46,11 @@ const { activeScheduleSessions } = require('./session-schedule-mark.js');
50
46
  const { HISTORY_FOR_ENRICH, sessionPreviewFor } = require('./session-preview.js');
51
47
  // 正文水位探针:进对话前问「宿主日志到哪个水位了」,现读一小段日志尾巴(见该文件头)。
52
48
  const { handleSessionHead } = require('./session-head.js');
49
+ // 新建会话(含 `isolate: true` 那条隔离工作目录的路):建树 / 回滚 / 登记一整段单列,
50
+ // 见该文件头。sessions.js 只剩转出,拆分上限才不会在这里被顶爆。
51
+ const { handleNew } = require('./session-new.js');
52
+ // 隔离工作树的自动回收:会话归档 / 被删 / 从宿主清单消失时把树收掉(见该文件头)。
53
+ const { sweepIsolationWorktrees } = require('./worktree-lifecycle.js');
53
54
 
54
55
  const SESSIONS_PREVIEW_LIMIT = 20; // 仅为最近/运行中的会话补最后消息预览
55
56
  const SESSION_LIST_CACHE_MS = 10000; // 会话列表增料缓存(降低手机轮询对桌面的冲击)
@@ -174,6 +175,13 @@ async function buildSessionsResponse(ctx, deviceKey = 'legacy', generation = com
174
175
  // 行首那只时钟的判据:这一条会话还有没有活动的自动化任务(见 session-schedule-mark.js)。
175
176
  // 与置顶 / 归档同一个位置取,一次目录查询喂满整份列表,别在渲染层逐行发请求。
176
177
  const scheduled = await activeScheduleSessions(ctx);
178
+ // 隔离工作树的回收(见 worktree-lifecycle.js):拿这一轮宿主清单 + 归档集合当「谁还活着」
179
+ // 的判据,把已经结束那些会话的树收掉。fire-and-forget —— 列表刷新是热点路径,删树失败
180
+ // 不能把这一发列表打坏;它自己有节流与在途锁。
181
+ void sweepIsolationWorktrees(ctx, {
182
+ liveSessionIds: summaries.filter((item) => item && typeof item.sessionId === 'string').map((item) => item.sessionId),
183
+ archivedSessionIds: archived,
184
+ });
177
185
  const allSummaries = summaries.filter((item) => item && !deleted.has(item.sessionId)
178
186
  && (archivedOnly === archived.has(item.sessionId)));
179
187
  // 状态跟踪覆盖完整列表,不能受预览补全上限影响。
@@ -333,86 +341,6 @@ async function handleStats(ctx, req, res) {
333
341
  sendJson(res, 200, { ok: true, projections: stats.projections });
334
342
  }
335
343
 
336
- /**
337
- * POST /api/mobile/v1/session/new(token){ workspaceId? | cwd? } → { ok, sessionId }
338
- * 新建一个空白会话。优先 workspaceId:宿主把新会话 attach 到该项目(workspace)
339
- * 的 sessionIds 账上,桌面端侧栏项目下立即可见;无 workspaceId 时回退 cwd
340
- * (不传则归属其默认/未分组工作区)。
341
- * 走宿主 apiProxy 的 session.create(接受 workspaceId 或 cwd,二者不能同时给)。
342
- *
343
- * cwd 进来之前必须落在**宿主已登记的工作区**里:会话的 cwd 就是 allowed-zone 的第二个
344
- * 根(见 allowed-zone.js 的 allowedRoots),随手塞一个 `/` 进来等于把整台机器变成
345
- * 「允许读写区」。工作区清单读不到时照实回 502,不按「没有工作区」处理 —— 那会让每个
346
- * 目录都变成 403,用户看到的是「我的目录突然不能用了」。
347
- */
348
- async function handleNew(ctx, req, res) {
349
- const body = await readJsonBody(req, 64 * 1024);
350
- const workspaceId = body && typeof body.workspaceId === 'string' && body.workspaceId.trim()
351
- ? body.workspaceId.trim()
352
- : '';
353
- // 只有走 cwd 那条路才需要校验:workspaceId 本身就把范围交给了宿主登记过的那一项。
354
- let cwd = '';
355
- if (!workspaceId && body && typeof body.cwd === 'string' && body.cwd.trim()) {
356
- const declared = body.cwd.trim();
357
- if (!path.isAbsolute(declared)) {
358
- return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: 'cwd 必须是绝对路径' } });
359
- }
360
- cwd = path.resolve(declared);
361
- let roots;
362
- try {
363
- roots = await workspaceRoots(ctx);
364
- } catch (error) {
365
- return sendJson(res, 502, {
366
- ok: false,
367
- error: {
368
- code: (error && error.code) || 'workspace-list-failed',
369
- message: String((error && error.message) || error),
370
- },
371
- });
372
- }
373
- if (!roots.some((root) => isWithin(root, cwd))) {
374
- return sendJson(res, 403, {
375
- ok: false,
376
- error: { code: 'outside-allowed', message: '这个目录不在能建会话的范围里(只能落在已登记的工作区)' },
377
- });
378
- }
379
- }
380
- // 新建会话是**非幂等**写:同一发请求被重投一次就会凭空多一个会话。requestId 由
381
- // App 在构造请求头时生成一次,内核换通道重投复用同一个 init(同一个头),重投于是
382
- // 命中这里、直接拿回第一次的 sessionId(见 mobile/idempotency.js)。
383
- const outcome = await withIdempotency(ctx, canonicalDeviceKey(req), requestIdOf(req, body), async () => {
384
- let payload = {};
385
- if (workspaceId) {
386
- payload.workspaceId = workspaceId;
387
- } else if (cwd) {
388
- payload.cwd = cwd;
389
- }
390
- // 宿主 session.create 接受 agentPreset:新建时直接定档,省掉「先建再 select」的
391
- // 两步(select 只在会话还没开跑时生效,新建后立刻 select 同样可行但多一次 RPC)。
392
- if (body && typeof body.agentPreset === 'string' && body.agentPreset.trim()) {
393
- payload.agentPreset = body.agentPreset.trim();
394
- }
395
- const { value, error } = unwrap(await callSessions(ctx, 'create', payload));
396
- if (error) return { status: 400, body: { ok: false, error } };
397
- const sessionId = value && typeof value.sessionId === 'string' ? value.sessionId : null;
398
- if (!sessionId) {
399
- return { status: 500, body: { ok: false, error: { code: 'internal', message: '新建会话未返回 sessionId' } } };
400
- }
401
- // 新建的会话要立刻出现在列表里,否则手机端最长 10 秒看不到它。
402
- invalidateSessionList(ctx);
403
- return {
404
- status: 200,
405
- body: {
406
- ok: true,
407
- sessionId,
408
- cwd: payload.cwd || null,
409
- ...(value && typeof value.agentPreset === 'string' ? { agentPreset: value.agentPreset } : {}),
410
- },
411
- };
412
- });
413
- sendJson(res, outcome.status, outcome.body);
414
- }
415
-
416
344
  /**
417
345
  * POST /api/mobile/v1/session/queue/update(token){ sessionId, itemId, action }
418
346
  * 排队消息条动作透传:edit(content) / remove / steer(插话发送,仅运行中)。