dsh-mobile-plugin 0.5.84 → 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.
@@ -1,3 +1,4 @@
1
+ // 对齐 Host-wide Schedule v2:保留 v1 sessionId/status,同时透传 target 与 CAS 元数据。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -6,8 +7,8 @@
6
7
  * 服务走同进程直查 `ctx.get('schedule')`,不写进 `inject`:它是 Typert Remote 服务、不在
7
8
  * apiProxy 命名空间里,写进 inject 会因为老宿主没有这个服务而挡住整个插件。
8
9
  *
9
- * 四条接口:catalog(全部任务)、list(该会话的任务)、history(一条任务的运行记录)、
10
- * delete(硬删)。update 不做:手机端没有编辑入口,接一条没人调的路只会多一份参数校验。
10
+ * 读取覆盖 catalog(全部任务)、list(参与该会话的任务)、view(按 id 读回)、
11
+ * history(真实投递记录);delete 共用宿主的 edit 与 CAS。编辑入口在 schedule-edit.js。
11
12
  *
12
13
  * list 走 `catalog()` 再按 sessionId 筛,不用宿主的 `list({sessionId})`:后者只回还在跑的
13
14
  * 任务、行上没有 sessionId / status,一次性任务跑完就会从手机上「凭空消失」。
@@ -90,21 +91,47 @@ function normalizeDeliveryRecord(item) {
90
91
  const scheduledAt = optionalText(item.scheduledAt, SCHEDULE_TIME_MAX);
91
92
  const deliveredAt = optionalText(item.deliveredAt, SCHEDULE_TIME_MAX);
92
93
  const prompt = optionalText(item.prompt, SCHEDULE_PROMPT_MAX);
94
+ const targetSessionId = optionalText(item.targetSessionId, SCHEDULE_ID_MAX);
93
95
  return {
94
96
  messageId,
95
97
  ...(scheduledAt === undefined ? {} : { scheduledAt }),
96
98
  ...(deliveredAt === undefined ? {} : { deliveredAt }),
97
99
  ...(prompt === undefined ? {} : { prompt }),
100
+ ...(targetSessionId === undefined ? {} : { targetSessionId }),
98
101
  };
99
102
  }
100
103
 
101
- /** 宿主回的最后一次投递:两个时间都在才留,缺一个就当没有。 */
104
+ /** 宿主回的最后一次投递:保留真实投递会话与消息,兼容旧回执只有两个时间。 */
102
105
  function normalizeLastDelivery(value) {
103
106
  if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
104
107
  const scheduledAt = optionalText(value.scheduledAt, SCHEDULE_TIME_MAX);
105
108
  const deliveredAt = optionalText(value.deliveredAt, SCHEDULE_TIME_MAX);
106
109
  if (scheduledAt === undefined || deliveredAt === undefined) return undefined;
107
- return { scheduledAt, deliveredAt };
110
+ const messageId = optionalText(value.messageId, SCHEDULE_ID_MAX);
111
+ const targetSessionId = optionalText(value.targetSessionId, SCHEDULE_ID_MAX);
112
+ return { scheduledAt, deliveredAt,
113
+ ...(messageId === undefined ? {} : { messageId }),
114
+ ...(targetSessionId === undefined ? {} : { targetSessionId }),
115
+ };
116
+ }
117
+
118
+ /** 只复制宿主支持的创建参数;空对象也是有效的默认创建规格。 */
119
+ function normalizeCreateSpec(value) {
120
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
121
+ const cwd = optionalText(value.cwd, 4096);
122
+ const agentPreset = optionalText(value.agentPreset, SCHEDULE_ID_MAX);
123
+ return { ...(cwd === undefined ? {} : { cwd }), ...(agentPreset === undefined ? {} : { agentPreset }) };
124
+ }
125
+
126
+ /** 保存态 target 与写请求不同:new_once 带宿主预留的 sessionId。 */
127
+ function normalizeStoredTarget(value, legacySessionId) {
128
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
129
+ const sessionId = optionalText(value.sessionId, SCHEDULE_ID_MAX);
130
+ if (value.kind === 'session' && sessionId) return { kind: 'session', sessionId };
131
+ if (value.kind === 'new_once') return { kind: 'new_once', ...(sessionId ? { sessionId } : {}), create: normalizeCreateSpec(value.create) };
132
+ if (value.kind === 'new') return { kind: 'new', create: normalizeCreateSpec(value.create) };
133
+ }
134
+ return legacySessionId ? { kind: 'session', sessionId: legacySessionId } : undefined;
108
135
  }
109
136
 
110
137
  /**
@@ -160,18 +187,36 @@ function normalizeScheduleEntry(item, sessionId, state) {
160
187
  if (typeof item.kind !== 'string' || !SCHEDULE_KINDS.has(item.kind)) return null;
161
188
  const title = requiredText(item.title, SCHEDULE_TITLE_MAX);
162
189
  if (!title) return null;
163
- // catalog 的会话归属在 target / involvedSessionIds 上,list 的由查询串那个顶上。
190
+ // 宿主级 new 任务尚未投递时可以没有会话;不能因此从目录中消失。
164
191
  const resolvedSessionId = sessionId || entrySessionId(item);
165
- if (!resolvedSessionId) return null;
166
-
192
+ const legacySessionId = requiredText(item.sessionId, SCHEDULE_ID_MAX);
193
+ const target = normalizeStoredTarget(item.target, legacySessionId);
194
+ if (!resolvedSessionId && !target) return null;
195
+ const involvedSessionIds = scheduleRowSessionIds({
196
+ involvedSessionIds: Array.isArray(item.involvedSessionIds) ? item.involvedSessionIds : (legacySessionId ? [legacySessionId] : []),
197
+ });
198
+ const status = ['active', 'paused', 'ended', 'inactive'].includes(item.status) ? item.status : 'active';
167
199
  const entry = {
168
200
  id,
169
201
  sessionId: resolvedSessionId,
170
202
  kind: item.kind,
171
203
  title,
172
204
  prompt: promptText(item.prompt),
173
- state: state || stateOf(item.status),
205
+ // state 保留旧 App 两档筛选,status 提供新版暂停 / 结束的精确状态。
206
+ state: state || stateOf(status),
207
+ status,
208
+ involvedSessionIds,
209
+ ...(target === undefined ? {} : { target }),
174
210
  };
211
+ const targetSessionId = optionalText(item.targetSessionId, SCHEDULE_ID_MAX)
212
+ || optionalText(target?.sessionId, SCHEDULE_ID_MAX)
213
+ || optionalText(item.lastDelivery?.targetSessionId, SCHEDULE_ID_MAX);
214
+ if (targetSessionId !== undefined) entry.targetSessionId = targetSessionId;
215
+ for (const key of ['createdAt', 'deliveryFloorEndsAt']) {
216
+ const value = optionalText(item[key], SCHEDULE_TIME_MAX);
217
+ if (value !== undefined) entry[key] = value;
218
+ }
219
+ if (item.executionActive === true) entry.executionActive = true;
175
220
 
176
221
  const scheduledAt = optionalText(item.scheduledAt, SCHEDULE_TIME_MAX);
177
222
  if (scheduledAt !== undefined) entry.scheduledAt = scheduledAt;
@@ -285,7 +330,10 @@ function sendFailure(res, error) {
285
330
  const code = error && typeof error.code === 'string' && error.code.trim()
286
331
  ? error.code.trim()
287
332
  : 'schedule_failed';
288
- sendJson(res, 502, { ok: false, error: { code, message: errorText(error) } });
333
+ const details = error?.details && typeof error.details === 'object' ? error.details : undefined;
334
+ sendJson(res, code === 'schedule_conflict' ? 409 : 502, {
335
+ ok: false, error: { code, message: errorText(error), ...(details === undefined ? {} : { details }) },
336
+ });
289
337
  }
290
338
 
291
339
  /** 从查询串取一个 trim 过的字符串参数。 */
@@ -345,7 +393,7 @@ async function handleScheduleList(ctx, req, res) {
345
393
 
346
394
  // 先按目录整体收敛(保住 status → state 的推导),再筛这条会话的。
347
395
  const all = normalizeScheduleEntries(value, undefined, undefined);
348
- const records = all.filter((entry) => entry.sessionId === sessionId);
396
+ const records = all.filter((entry) => scheduleRowSessionIds(entry).includes(sessionId));
349
397
  if (queryValue(url, 'brief') === '1') {
350
398
  const active = records
351
399
  .filter((entry) => entry.state === 'active')
@@ -379,13 +427,34 @@ function normalizeRetention(value) {
379
427
  };
380
428
  }
381
429
 
430
+ /** GET /api/mobile/v1/schedule/view?id=…[&sessionId=…]:优先宿主 view,旧宿主回退 catalog。 */
431
+ async function handleScheduleView(ctx, req, res) {
432
+ const url = new URL(req.url, 'http://x');
433
+ const id = queryValue(url, 'id');
434
+ if (!id) return sendJson(res, 400, { ok: false, error: { code: 'invalid_selector', message: '需要 id' } });
435
+ const service = scheduleService(ctx);
436
+ if (!service) return sendUnavailable(res);
437
+ let value;
438
+ try {
439
+ if (typeof service.view === 'function') value = await service.view({ id });
440
+ else if (typeof service.catalog === 'function') {
441
+ const entry = normalizeScheduleEntries(await service.catalog(), undefined, undefined).find((item) => item.id === id);
442
+ value = entry || { id, code: 'schedule_not_found' };
443
+ } else return sendUnavailable(res);
444
+ } catch (error) { return sendFailure(res, error); }
445
+ if (value && value.code === 'schedule_not_found') return sendJson(res, 404, { ok: false, error: { code: 'schedule_not_found', message: '没有这条定时任务' } });
446
+ const record = normalizeScheduleEntry(value, '', undefined);
447
+ if (!record) return sendFailure(res, new Error('宿主返回的任务形状不对'));
448
+ sendJson(res, 200, { ok: true, record, serverNow: Date.now() });
449
+ }
450
+
382
451
  /** GET /api/mobile/v1/schedule/history?sessionId=…&id=…&limit=20&before=… */
383
452
  async function handleScheduleHistory(ctx, req, res) {
384
453
  const url = new URL(req.url, 'http://x');
385
454
  const sessionId = queryValue(url, 'sessionId');
386
455
  const id = queryValue(url, 'id');
387
- if (!sessionId || !id) {
388
- return sendJson(res, 400, { ok: false, error: { code: 'invalid_selector', message: '需要 sessionId 与 id' } });
456
+ if (!id) {
457
+ return sendJson(res, 400, { ok: false, error: { code: 'invalid_selector', message: '需要 id' } });
389
458
  }
390
459
 
391
460
  const limit = parseLimit(url.searchParams.get('limit'));
@@ -402,13 +471,15 @@ async function handleScheduleHistory(ctx, req, res) {
402
471
  const service = scheduleService(ctx);
403
472
  if (!service) return sendUnavailable(res);
404
473
 
405
- const payload = { sessionId, id, limit };
474
+ const payload = { id, limit };
406
475
  const before = queryValue(url, 'before');
407
476
  if (before) payload.before = before;
408
477
 
409
478
  let value;
410
479
  try {
411
- value = await service.history(payload);
480
+ if (typeof service.remoteHistory === 'function') value = await service.remoteHistory(payload);
481
+ else if (typeof service.history === 'function') value = await service.history({ ...(sessionId ? { sessionId } : {}), ...payload });
482
+ else return sendUnavailable(res);
412
483
  } catch (error) {
413
484
  return sendFailure(res, error);
414
485
  }
@@ -453,10 +524,10 @@ async function handleScheduleHistory(ctx, req, res) {
453
524
  * —— 后者只认 id,存储本来就是全局一张表,行上的 sessionId 只是字段(见 A2-57 的坑)。
454
525
  * 先问 `edit`,宿主没有这个方法再退回老的 `delete`。
455
526
  */
456
- async function deleteTask(service, sessionId, id) {
457
- if (typeof service.edit === 'function') {
458
- return service.edit({ id, action: 'delete' });
459
- }
527
+ async function deleteTask(service, sessionId, id, expectedUpdatedAt) {
528
+ const request = { id, action: 'delete', ...(expectedUpdatedAt === undefined ? {} : { expectedUpdatedAt }) };
529
+ if (typeof service.remoteEdit === 'function') return service.remoteEdit(request);
530
+ if (typeof service.edit === 'function') return service.edit(request);
460
531
  return service.delete({ sessionId, id });
461
532
  }
462
533
 
@@ -465,21 +536,23 @@ async function handleScheduleDelete(ctx, req, res) {
465
536
  const body = (await readJsonBody(req)) || {};
466
537
  const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : '';
467
538
  const id = typeof body.id === 'string' ? body.id.trim() : '';
468
- if (!sessionId || !id) {
469
- return sendJson(res, 400, { ok: false, error: { code: 'invalid_selector', message: '需要 sessionId 与 id' } });
470
- }
471
-
539
+ if (!id) return sendJson(res, 400, { ok: false, error: { code: 'invalid_selector', message: '需要 id' } });
472
540
  const service = scheduleService(ctx);
473
541
  if (!service) return sendUnavailable(res);
474
-
542
+ if (!sessionId && typeof service.remoteEdit !== 'function' && typeof service.edit !== 'function') {
543
+ return sendJson(res, 400, { ok: false, error: { code: 'invalid_selector', message: '旧宿主删除需要 sessionId' } });
544
+ }
475
545
  let value;
476
546
  try {
477
- value = await deleteTask(service, sessionId, id);
547
+ value = await deleteTask(service, sessionId, id, body.expectedUpdatedAt);
478
548
  } catch (error) {
479
549
  return sendFailure(res, error);
480
550
  }
481
551
 
482
552
  const source = value && typeof value === 'object' ? value : {};
553
+ if (source.code === 'schedule_conflict') return sendJson(res, 409, { ok: false, id, code: source.code,
554
+ error: { code: source.code, message: typeof source.message === 'string' ? source.message : '这条任务刚被改过,刷新后再试',
555
+ ...(source.details && typeof source.details === 'object' ? { details: source.details } : {}) } });
483
556
  // 任务已经不在了不算失败:手机端刷新后本来就看不到它,报错只会弹一个没意义的红条。
484
557
  const notFound = source.deleted !== true && source.code === 'schedule_not_found';
485
558
  sendJson(res, 200, {
@@ -493,6 +566,7 @@ async function handleScheduleDelete(ctx, req, res) {
493
566
  module.exports = {
494
567
  handleScheduleCatalog,
495
568
  handleScheduleList,
569
+ handleScheduleView,
496
570
  handleScheduleHistory,
497
571
  handleScheduleDelete,
498
572
  entrySessionId,
@@ -1,3 +1,4 @@
1
+ // 官方工作树请求在会话创建后登记,首消息等待交给宿主;旧宿主保留已有隔离流程。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -30,6 +31,7 @@ const { withIdempotency, requestIdOf } = require('./idempotency.js');
30
31
  const { canonicalDeviceKey, invalidateSessionList } = require('./session-cache.js');
31
32
  const { unwrap } = require('./envelope.js');
32
33
  const { callSessions } = require('./rpc.js');
34
+ const { capabilitiesOf: forgeCapabilities, requestForNew } = require('./forge-worktree.js');
33
35
  const {
34
36
  createIsolationWorktreeForNew, releaseIsolationWorktree, bindSession,
35
37
  } = require('./worktree-isolation.js');
@@ -72,6 +74,10 @@ async function handleNew(ctx, req, res) {
72
74
  : '';
73
75
  const isolate = !!(body && body.isolate === true);
74
76
  const keepWorktree = !!(body && body.keepWorktree === true);
77
+ const hostWorktree = isolate && forgeCapabilities(ctx).worktree.create;
78
+ if (hostWorktree && keepWorktree) {
79
+ return sendJson(res, 400, { ok: false, error: { code: 'worktree-keep-unsupported', message: '官方工作树没有逐棵保留策略' } });
80
+ }
75
81
  // 隔离那条路要一个可解析的项目落点:优先 workspaceId,其次调用方给的 cwd。
76
82
  let projectCwd = '';
77
83
  // 只有走 cwd 那条路才需要校验:workspaceId 本身就把范围交给了宿主登记过的那一项。
@@ -118,7 +124,11 @@ async function handleNew(ctx, req, res) {
118
124
  let payload = {};
119
125
  // 这一次请求建的那棵树:create 失败时按它回滚。
120
126
  let isolated = null;
121
- if (isolate) {
127
+ if (hostWorktree) {
128
+ // 先在项目中创建会话,再向官方 Forge 记录请求;第一条消息由宿主等待建树。
129
+ if (workspaceId) payload.workspaceId = workspaceId;
130
+ else if (cwd) payload.cwd = cwd;
131
+ } else if (isolate) {
122
132
  // 建树失败就整次失败:不退回「就在原目录建会话」,否则用户以为已经隔离了、实际还在
123
133
  // 跟别人抢同一批文件。
124
134
  try {
@@ -1,3 +1,4 @@
1
+ // rc.5 子代理目录与 prompt 约定:external 只展示,续话能力由宿主能力探测决定。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -11,9 +12,12 @@
11
12
  * 重建(形状仍是 entries + parentAvailable);本文件只做形状收敛、限长与限条数。
12
13
  */
13
14
 
15
+ const crypto = require('node:crypto');
14
16
  const { sendJson, readJsonBody } = require('../shared/http-util');
15
17
  const { unwrap } = require('./sessions.js');
16
18
  const { promptOnceFor } = require('./session-cache.js');
19
+ const { inlineUploadedImageBlocks } = require('./uploads.js');
20
+ const { subagentPromptCapabilities } = require('./host-bridge/endpoints.js');
17
21
 
18
22
  // 子代理条数上限。长程会话实测能派到两百多个(反馈 #19 / #20),早先的 100 会把后面的整段
19
23
  // 静默截掉、手机上看不见也点不进。现在按实际数量取,只留一个防异常宿主的兜底量级。
@@ -23,10 +27,10 @@ const SUBAGENT_LABEL_MAX = 200; // 条目显示名截断长度
23
27
  // 0.2.0 的会话投影多了第三种 mode 'unknown':目录说这条子会话存在,但宿主还没读到
24
28
  // 它的子代理身份(session/subagent 投影没算出来),所以既不能当成一次性也不能当成
25
29
  // 可继续。桌面端对它的处理是当只读 + 显示「模式未知」,这里跟着放行。
26
- const SUBAGENT_MODES = new Set(['one-shot', 'continuable', 'unknown']);
30
+ const SUBAGENT_MODES = new Set(['one-shot', 'continuable', 'unknown', 'external']);
27
31
  const SUBAGENT_ACTIVITIES = new Set(['running', 'inactive']);
28
32
  const SUBAGENT_REASONS = new Set(['corrupt', 'unsupported', 'unavailable']);
29
- const SUBAGENT_PROMPT_MAX_BODY = 256 * 1024; // 续话请求体上限(只有文本,图片已拒)
33
+ const SUBAGENT_PROMPT_MAX_BODY = Math.ceil(8 * 1024 * 1024 * 4 / 3); // 与主会话图片请求同档,宿主再做附件限制
30
34
  const SUBAGENT_PROMPT_MAX_BLOCKS = 32; // content 块数上限
31
35
  const SUBAGENT_PROMPT_MAX_TEXT = 64 * 1024; // 单条 text 块字符上限
32
36
  const SUBAGENT_INTERRUPT_MAX_BODY = 64 * 1024;
@@ -62,7 +66,15 @@ function normalizeSubagentEntry(item) {
62
66
 
63
67
  if (item.kind === 'diagnostic') {
64
68
  if (!SUBAGENT_REASONS.has(item.reason)) return null;
65
- return { kind: 'diagnostic', id, reason: item.reason };
69
+ const relation = {};
70
+ for (const key of ['name', 'description', 'path']) {
71
+ const text = normalizeLabel(item[key]);
72
+ if (text !== undefined) relation[key] = text;
73
+ }
74
+ const parentSessionId = normalizeId(item.parentSessionId || item.parentId);
75
+ if (parentSessionId) Object.assign(relation, { parentId: parentSessionId, parentSessionId });
76
+ if (Number.isInteger(item.depth) && item.depth >= 1 && item.depth <= 128) relation.depth = item.depth;
77
+ return { kind: 'diagnostic', id, reason: item.reason, ...relation };
66
78
  }
67
79
 
68
80
  if (item.kind !== 'child') return null;
@@ -71,13 +83,20 @@ function normalizeSubagentEntry(item) {
71
83
  if (typeof item.hasChildren !== 'boolean') return null;
72
84
 
73
85
  const label = normalizeLabel(item.label);
86
+ const name = normalizeLabel(item.name);
87
+ const description = typeof item.description === 'string' && item.description.trim() ? item.description.trim() : undefined;
88
+ const parentSessionId = normalizeId(item.parentSessionId || item.parentId);
89
+ const path = typeof item.path === 'string' && item.path.trim() ? item.path.trim() : undefined;
90
+ const depth = Number.isInteger(item.depth) && item.depth >= 1 && item.depth <= 128 ? item.depth : undefined;
74
91
  return {
75
- kind: 'child',
76
- id,
77
- mode: item.mode,
78
- activity: item.activity,
79
- hasChildren: item.hasChildren,
92
+ kind: 'child', id, mode: item.mode, activity: item.activity, hasChildren: item.mode === 'external' ? false : item.hasChildren,
93
+ ...(name === undefined ? {} : { name }),
80
94
  ...(label === undefined ? {} : { label }),
95
+ ...(description === undefined ? {} : { description }),
96
+ ...(parentSessionId === '' ? {} : { parentSessionId, parentId: parentSessionId }),
97
+ ...(path === undefined ? {} : { path }),
98
+ ...(depth === undefined ? {} : { depth }),
99
+ ...(item.mode !== 'continuable' ? { targetAvailable: false } : typeof item.targetAvailable === 'boolean' ? { targetAvailable: item.targetAvailable } : item.targetAvailable === null ? { targetAvailable: null } : {}),
81
100
  };
82
101
  }
83
102
 
@@ -97,7 +116,14 @@ function normalizeSubagentList(value) {
97
116
  entries.push(entry);
98
117
  if (entries.length >= SUBAGENT_MAX_ENTRIES) break;
99
118
  }
100
- return { entries, parentAvailable: Boolean(value && value.parentAvailable === true) };
119
+ const rootSessionId = normalizeId(value && value.rootSessionId);
120
+ const rootAvailable = value && value.rootAvailable;
121
+ return {
122
+ entries,
123
+ parentAvailable: Boolean(value && value.parentAvailable === true),
124
+ ...(rootSessionId ? { rootSessionId } : {}),
125
+ ...(typeof rootAvailable === 'boolean' || rootAvailable === null ? { rootAvailable } : {}),
126
+ };
101
127
  }
102
128
 
103
129
  /** GET /api/mobile/v1/subagents?sessionId=… —— 这个会话派出去的子代理目录(只读)。 */
@@ -117,7 +143,7 @@ async function handleSubagents(ctx, req, res) {
117
143
  }, controller.signal));
118
144
  if (error) return sendJson(res, 400, { ok: false, error });
119
145
 
120
- sendJson(res, 200, { ok: true, ...normalizeSubagentList(value) });
146
+ sendJson(res, 200, { ok: true, ...normalizeSubagentList(value), capabilities: subagentCapabilities(ctx) });
121
147
  }
122
148
 
123
149
  /** 从请求体里取一个必填的会话 id(trim 后仍为空就当没给)。 */
@@ -129,12 +155,14 @@ function readId(body, key) {
129
155
  /**
130
156
  * 把续话请求的 content 收敛成宿主 subagent.prompt 认的形状。
131
157
  *
132
- * 与 /session/send 同一套规则,但**图片一律拒绝**:桌面端在路由之前就把带 image 的
133
- * 续话判成 attachment-error / SUBAGENT_IMAGE_UNSUPPORTED(runtime 的 subagent 分支
134
- * 只把 text 块 flatMap 出去,图片根本到不了宿主)。这里跟着拒,免得静默丢块让用户
135
- * 以为图发出去了。
158
+ * 图片仅在宿主严格 prompt descriptor 明确支持时开放;未知与旧宿主保留原来的拒绝码。
159
+ * uploadId 只在插件上传暂存区解析,最终字节仍交宿主附件服务做准入与持久化。
136
160
  */
137
- function normalizePromptContent(body) {
161
+ function subagentCapabilities(ctx) {
162
+ return subagentPromptCapabilities(ctx);
163
+ }
164
+
165
+ function normalizePromptContent(body, options = {}) {
138
166
  let content;
139
167
  if (Array.isArray(body.content)) content = body.content;
140
168
  else if (typeof body.text === 'string' && body.text.trim()) content = [{ type: 'text', text: body.text }];
@@ -151,13 +179,13 @@ function normalizePromptContent(body) {
151
179
  return { error: { code: 'bad-request', message: 'content 块缺少 type' } };
152
180
  }
153
181
  if (block.type === 'image') {
154
- return {
155
- error: {
156
- code: 'attachment-error',
157
- message: '子代理续话不支持图片输入。',
158
- details: { reason: 'SUBAGENT_IMAGE_UNSUPPORTED' },
159
- },
160
- };
182
+ if (options.images !== true) return { error: { code: 'attachment-error', message: '子代理续话不支持图片输入。', details: { reason: 'SUBAGENT_IMAGE_UNSUPPORTED' } } };
183
+ const mediaTypes = ['image/png', 'image/jpeg', 'image/webp', 'image/gif'];
184
+ const inline = typeof block.data === 'string' && block.data.length > 0;
185
+ const uploaded = typeof block.uploadId === 'string' && block.uploadId.length > 0;
186
+ if (!mediaTypes.includes(block.mediaType) || (!inline && !uploaded)) return { error: { code: 'bad-request', message: 'image 块需合法 mediaType 与 base64 data 或 uploadId' } };
187
+ blocks.push({ type: 'image', mediaType: block.mediaType, ...(inline ? { data: block.data } : { uploadId: block.uploadId }), ...(typeof block.name === 'string' && block.name ? { name: block.name } : {}) });
188
+ continue;
161
189
  }
162
190
  if (block.type !== 'text') {
163
191
  return { error: { code: 'bad-request', message: `不支持的 content 块类型: ${block.type}` } };
@@ -181,8 +209,8 @@ function normalizePromptContent(body) {
181
209
  * 所以续话必须走 subagent.prompt。mode 固定 continuable:一次性子代理宿主压根
182
210
  * 不接受续话(桌面端也是先判 one-shot 再拒绝),这里不给客户端挑的机会。
183
211
  *
184
- * 宿主还要求父会话「在线」(ctx.agents.get(parentSessionId) 有值),否则回
185
- * subagent-parent-unavailable —— 这一条原样透传给 App,由它决定提示什么。
212
+ * 新宿主按真实树根投递,创建者可以离线;目录中的 rootAvailable 仅供界面提示,
213
+ * 最终投递准入仍由宿主校验,拒绝码原样返回。
186
214
  */
187
215
  async function handleSubagentPrompt(ctx, req, res) {
188
216
  const body = await readJsonBody(req, SUBAGENT_PROMPT_MAX_BODY);
@@ -194,13 +222,21 @@ async function handleSubagentPrompt(ctx, req, res) {
194
222
  error: { code: 'bad-request', message: '需要 { parentSessionId, childSessionId, content | text }' },
195
223
  });
196
224
  }
197
- const normalized = normalizePromptContent(body);
225
+ const capabilities = subagentCapabilities(ctx);
226
+ const delivery = body.delivery === undefined ? 'queue' : body.delivery;
227
+ if (delivery !== 'queue' && delivery !== 'steer') return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: "delivery 必须为 'queue' 或 'steer'" } });
228
+ if (delivery === 'steer' && capabilities.steer !== true) return sendJson(res, 400, { ok: false, error: { code: 'subagent-prompt-unsupported', message: '这台宿主未确认支持子代理插话投递', details: { reason: 'SUBAGENT_STEER_UNSUPPORTED' } } });
229
+ const normalized = normalizePromptContent(body, capabilities);
198
230
  if (normalized.error) return sendJson(res, 400, { ok: false, error: normalized.error });
231
+ const expired = await inlineUploadedImageBlocks(normalized.blocks);
232
+ if (expired) return sendJson(res, 400, { ok: false, error: { code: 'upload-not-found', message: expired } });
233
+ for (const block of normalized.blocks) if (block.type === 'image') delete block.uploadId;
199
234
 
200
235
  const clientTimeZone = typeof body.clientTimeZone === 'string' && body.clientTimeZone.trim()
201
236
  ? body.clientTimeZone.trim()
202
237
  : undefined;
203
238
  const clientMessageId = typeof body.clientMessageId === 'string' ? body.clientMessageId.trim() : '';
239
+ const requestId = typeof body.requestId === 'string' && body.requestId.trim() ? body.requestId.trim() : clientMessageId || `mobile-subagent-${crypto.randomUUID()}`;
204
240
 
205
241
  const controller = new AbortController();
206
242
  const call = () => ctx.apiProxy.subagents.prompt({
@@ -211,6 +247,7 @@ async function handleSubagentPrompt(ctx, req, res) {
211
247
  childSessionId,
212
248
  mode: 'continuable',
213
249
  content: normalized.blocks,
250
+ ...(capabilities.delivery === true || body.requestId ? { requestId, delivery } : {}),
214
251
  ...(clientTimeZone === undefined ? {} : { clientTimeZone }),
215
252
  },
216
253
  }, controller.signal);
@@ -261,4 +298,5 @@ module.exports = {
261
298
  normalizeSubagentEntry,
262
299
  normalizeSubagentList,
263
300
  normalizePromptContent,
301
+ subagentCapabilities,
264
302
  };
@@ -1,3 +1,4 @@
1
+ // 官方工作树不进入 legacy 登记;旧宿主仍保留已有隔离创建与存量回收。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -99,7 +100,8 @@ function entryKeyOf({ sessionId, reuseKey }) {
99
100
  * `branch` / `baseSha` 是后加的字段:老登记记录里没有它们,读的地方一律按「可能没有」处理,
100
101
  * 别的地方照着旧形状写出来的记录也照样能用。
101
102
  */
102
- function recordIsolation({ sessionId, reuseKey, repoRoot, cwd, keep, branch, baseSha }) {
103
+ function recordIsolation({ sessionId, reuseKey, repoRoot, cwd, keep, branch, baseSha, owner }) {
104
+ if (owner === 'host') return;
103
105
  const key = entryKeyOf({ sessionId, reuseKey });
104
106
  if (!key || !repoRoot || !cwd) return;
105
107
  const state = readRegistry();
@@ -108,6 +110,8 @@ function recordIsolation({ sessionId, reuseKey, repoRoot, cwd, keep, branch, bas
108
110
  repoRoot,
109
111
  cwd,
110
112
  ...(sessionId ? { sessionId } : {}),
113
+ // 只记录插件自己创建的旧工作树;官方 Forge worktree 不进入这张表,避免双重回收。
114
+ owner: 'legacy',
111
115
  keep: keep === true,
112
116
  createdAt: (previous && previous.createdAt) || Date.now(),
113
117
  ...(branch ? { branch } : {}),
@@ -117,7 +121,8 @@ function recordIsolation({ sessionId, reuseKey, repoRoot, cwd, keep, branch, bas
117
121
  }
118
122
 
119
123
  /** 把一条会话挂到已经建好的那棵树上(建树时还不知道会话号)。 */
120
- function bindSession(sessionId, { cwd, repoRoot, reuseKey, keep, branch, baseSha }) {
124
+ function bindSession(sessionId, { cwd, repoRoot, reuseKey, keep, branch, baseSha, owner }) {
125
+ if (owner === 'host') return;
121
126
  if (typeof sessionId !== 'string' || !sessionId) return;
122
127
  const state = readRegistry();
123
128
  const stale = entryKeyOf({ reuseKey });
@@ -130,6 +135,7 @@ function bindSession(sessionId, { cwd, repoRoot, reuseKey, keep, branch, baseSha
130
135
  repoRoot: (fromReuse && fromReuse.repoRoot) || repoRoot,
131
136
  cwd: (fromReuse && fromReuse.cwd) || cwd,
132
137
  sessionId,
138
+ owner: 'legacy',
133
139
  keep: keep === true || Boolean(fromReuse && fromReuse.keep),
134
140
  createdAt: (fromReuse && fromReuse.createdAt) || Date.now(),
135
141
  ...(branchName ? { branch: branchName } : {}),
@@ -394,10 +400,11 @@ function recordOfCwd(cwd) {
394
400
  * `dropBranchIfUnused`),有提交就留着,用户的活不会跟着树一起没。分支信息优先用参数,
395
401
  * 没给就从登记表里查 —— 建树回滚那条路就是只传目录进来的。
396
402
  */
397
- async function releaseIsolationWorktree({ repoRoot, cwd, keep, branch, baseSha } = {}) {
398
- if (keep === true) return false;
403
+ async function releaseIsolationWorktree({ repoRoot, cwd, keep, branch, baseSha, owner } = {}) {
404
+ if (owner === 'host' || keep === true) return false;
399
405
  if (!repoRoot || !cwd) return false;
400
406
  const registered = recordOfCwd(cwd);
407
+ if (registered && registered.owner && registered.owner !== 'legacy') return false;
401
408
  const branchName = branch || (registered && registered.branch) || '';
402
409
  const base = baseSha || (registered && registered.baseSha) || '';
403
410
  // 目录已经不在了(用户手工删过 / 上一轮就 prune 掉了):没什么可收的,把登记表里
@@ -451,6 +458,7 @@ async function releaseForSessions(sessionIds) {
451
458
  for (const sessionId of ids) {
452
459
  const entry = state.entries[`session:${sessionId}`];
453
460
  if (!entry) continue;
461
+ if (entry.owner && entry.owner !== 'legacy') { out.kept.push(sessionId); continue; }
454
462
  if (entry.keep === true) { out.kept.push(sessionId); continue; }
455
463
  // 分支名与基线由 releaseIsolationWorktree 按目录从登记表里取。
456
464
  const ok = await releaseIsolationWorktree({ repoRoot: entry.repoRoot, cwd: entry.cwd });
@@ -1,3 +1,4 @@
1
+ // 只回收 legacy 登记的工作树;官方 Forge 工作树由宿主归档服务负责。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -55,6 +56,7 @@ async function sweepIsolationWorktrees(ctx, alive = {}, options = {}) {
55
56
  const dead = [];
56
57
  for (const [key, entry] of Object.entries(registeredIsolations())) {
57
58
  if (!key.startsWith('session:')) continue;
59
+ if (entry && entry.owner && entry.owner !== 'legacy') continue;
58
60
  const sessionId = key.slice('session:'.length);
59
61
  if (entry && entry.keep === true) continue;
60
62
  if (archived.has(sessionId) || !live.has(sessionId)) dead.push(sessionId);