dsh-mobile-ios 0.0.0-stage → 0.2.2

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.
@@ -0,0 +1,437 @@
1
+ // adapter/mock-host.mjs — 用契约夹具驱动宿主(决策 D3:Mock 载体)
2
+ // 目的:让客户端与网关在真实宿主不可用时也能跑到端到端;它不模拟"智能",
3
+ // 只忠实回放契约里已有的报文形状,避免 UI 在假数据上长歪。
4
+
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { fail, newId } from '../protocol.mjs';
9
+
10
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
11
+ // 目录重构后:夹具统一在项目根的 spec/fixtures/(gateway/src/adapter → 上三级即项目根)
12
+ const DEFAULT_FIXTURES = path.resolve(HERE, '../../../spec/fixtures');
13
+
14
+ const read = (dir, name) => JSON.parse(fs.readFileSync(path.join(dir, name), 'utf8'));
15
+
16
+ export function createMockHost({ fixturesDir = DEFAULT_FIXTURES, log = () => {}, autoPlay = false, speed = 1 } = {}) {
17
+ const hostInfo = read(fixturesDir, 'host/host.info.json').response.body;
18
+ const listBody = read(fixturesDir, 'tasks/tasks.list.json').response.body;
19
+ const detail = read(fixturesDir, 'tasks/task.detail.json').response.body;
20
+ const createOk = read(fixturesDir, 'tasks/task.create.ok.json').response.body;
21
+ const messageOk = read(fixturesDir, 'tasks/task.message.ok.json').response.body;
22
+ const cancelOk = read(fixturesDir, 'tasks/task.cancel.ok.json').response.body;
23
+ const artifacts = read(fixturesDir, 'tasks/task.artifacts.json').response.body;
24
+ const todoOk = read(fixturesDir, 'tasks/todo.answer.ok.json').response.body;
25
+ const scenario = read(fixturesDir, 'ws/stream.running.json');
26
+
27
+ const tasks = new Map(listBody.items.map((t) => [t.taskId, { ...t }]));
28
+ // 工作区分组:与 cordis alike,从夹具顶层 workspaces 下发,任务行带同源 id/name。
29
+ const workspaces = Array.isArray(listBody.workspaces) ? listBody.workspaces : [];
30
+ // 会话动作的 mock 状态(2026-11-18):置顶/归档集合,与桌面端 workspaceRegistry 同语义。
31
+ // 列表快照据此带 pinned/archived 标记,长按菜单的「取消置顶/取消归档」才能被验证。
32
+ const pinnedIds = new Set();
33
+ const archivedIds = new Set();
34
+ // 会话设置的 mock 状态(2026-11-17 同步面):权限当前值 + 每任务模型选择。
35
+ const sessionModels = new Map();
36
+ const MOCK_PERMISSION_OPTIONS = [
37
+ { value: 'requireApproval', name: '需审批', description: '每一步写入与命令都需要确认' },
38
+ { value: 'autoApprove', name: '自动批准', description: '跳过确认,按默认策略执行' },
39
+ { value: 'readOnly', name: '只读', description: '只允许读取,不改动任何文件' },
40
+ ];
41
+ const MOCK_MODEL_GROUPS = [
42
+ {
43
+ id: 'deepseek', name: 'DeepSeek',
44
+ models: [
45
+ { id: 'deepseek-chat', name: 'DeepSeek Chat' },
46
+ { id: 'deepseek-reasoner', name: 'DeepSeek Reasoner', defaultEffort: 'medium' },
47
+ ],
48
+ },
49
+ {
50
+ id: 'openai', name: 'OpenAI',
51
+ models: [{ id: 'gpt-5.2', name: 'GPT-5.2', defaultEffort: 'high' }],
52
+ },
53
+ ];
54
+ const modelOf = (taskId) => sessionModels.get(taskId) ?? { provider: 'deepseek', model: 'deepseek-chat' };
55
+ const subscribers = new Set();
56
+ const timers = new Set();
57
+ let playing = null;
58
+
59
+ // 宿主历史记录(2026-11-18 补齐 mock 冷启动历史缺口):
60
+ // 之前 mock 没有 events 面,GET /tasks/:id/events 永远 4500,
61
+ // 手机端冷启动时间线永远是空的——mock 截图验证不了气泡/时间戳。
62
+ // 记录形状与宿主对齐(session-history.mjs 的翻译输入):{type, seq, time(ms), data}。
63
+ const history = new Map(); // taskId -> [record]
64
+ const record = (taskId, type, data, at) => {
65
+ const list = history.get(taskId) ?? [];
66
+ list.push({
67
+ type,
68
+ seq: list.length + 1,
69
+ time: at ? Date.parse(at) || Date.now() : Date.now(),
70
+ data,
71
+ });
72
+ history.set(taskId, list);
73
+ };
74
+
75
+ const emit = (taskId, kind, data, at) => {
76
+ // 同步落一份宿主形状的历史记录(只落时间线会渲染的,噪声不搬)。
77
+ host.ingestExternal(taskId, kind, data, at);
78
+ for (const fn of subscribers) fn({ taskId, kind, data, at });
79
+ };
80
+
81
+ const clearTimers = () => {
82
+ for (const t of timers) clearTimeout(t);
83
+ timers.clear();
84
+ playing = null;
85
+ };
86
+
87
+ const host = {
88
+ kind: 'mock',
89
+ info: () => ({ ...hostInfo, caps: [...hostInfo.caps] }),
90
+
91
+ /**
92
+ * 外部注入的帧(dev 端点 /__mock/emit 直发 core,绕过 host.emit)也
93
+ * 落一份宿主形状的历史记录,保证 events() 与 WS 看到同一个世界。
94
+ */
95
+ ingestExternal(taskId, kind, data, at) {
96
+ if (kind !== 'turn' || !data || typeof data !== 'object') return;
97
+ if (data.type === 'user_message') {
98
+ record(taskId, 'user/message', {
99
+ content: [{ type: 'text', text: String(data.text ?? '') }],
100
+ source: { kind: 'user' },
101
+ }, at);
102
+ } else if (data.type === 'thought_delta') {
103
+ record(taskId, 'assistant/message', {
104
+ turn: 1,
105
+ message: { content: [{ type: 'reasoning', text: String(data.delta ?? '') }] },
106
+ }, at);
107
+ } else if (data.type === 'assistant_delta') {
108
+ record(taskId, 'assistant/message', {
109
+ turn: 1,
110
+ message: { content: [{ type: 'text', text: String(data.delta ?? '') }] },
111
+ }, at);
112
+ } else if (data.type === 'tool_call') {
113
+ record(taskId, 'tool/call', {
114
+ turn: 1, callId: data.callId ?? newId('call'),
115
+ name: data.toolName ?? 'tool', arguments: data.argSummary ?? '',
116
+ }, at);
117
+ } else if (data.type === 'tool_result') {
118
+ record(taskId, 'tool/result', {
119
+ turn: 1, toolCallId: data.callId ?? newId('call'), name: data.toolName,
120
+ content: [{ type: 'text', text: String(data.summary ?? '') }],
121
+ }, at);
122
+ }
123
+ },
124
+
125
+ async listTasks({ status, limit = 50, includeArchived = false } = {}) {
126
+ // 与 cordis 同口径(桌面端 tree.ts isVisible):置顶优先;
127
+ // 子会话 / 空占位不进任务条;归档默认隐藏,只在 includeArchived 视图出现。
128
+ const all = [...tasks.values()]
129
+ .map((t) => ({ ...t, pinned: pinnedIds.has(t.taskId), archived: archivedIds.has(t.taskId) }))
130
+ .filter((t) => !status || t.status === status)
131
+ .filter((t) => t.origin !== 'subagent' && !t.parentSessionId)
132
+ .filter((t) => !(t.blank === true && t.status !== 'running'))
133
+ .filter((t) => (includeArchived ? t.archived : !t.archived));
134
+ all.sort((a, b) => (Number(b.pinned) - Number(a.pinned))
135
+ || (Date.parse(b.lastActivityAt ?? 0) - Date.parse(a.lastActivityAt ?? 0)));
136
+ return {
137
+ items: all.slice(0, limit),
138
+ workspaces,
139
+ nextCursor: null,
140
+ serverTime: new Date().toISOString(),
141
+ };
142
+ },
143
+
144
+ async getTask(taskId) {
145
+ const t = tasks.get(taskId);
146
+ if (!t) throw fail(4011);
147
+ const flags = { pinned: pinnedIds.has(taskId), archived: archivedIds.has(taskId) };
148
+ if (taskId === detail.task.taskId) {
149
+ return { ...detail, task: { ...detail.task, ...t, ...flags }, lastSeq: 0, serverTime: new Date().toISOString() };
150
+ }
151
+ return {
152
+ task: { ...t, ...flags, lastSeq: 0 },
153
+ budget: { limitMin: t.budgetMin ?? 10, usedSec: t.elapsedSec ?? 0, remainingSec: 600, warnAt: 480 },
154
+ pendingTodos: [],
155
+ artifactsPreview: [],
156
+ tokenUsage: null,
157
+ lastSeq: 0,
158
+ serverTime: new Date().toISOString(),
159
+ };
160
+ },
161
+
162
+ async listArtifacts(taskId) {
163
+ if (!tasks.has(taskId)) throw fail(4011);
164
+ return artifacts;
165
+ },
166
+
167
+ /** mock 侧不碰磁盘:产物内容是固定文本,够客户端验证「点开→预览」这条链路。 */
168
+ async readArtifact(taskId, artifactId) {
169
+ if (!tasks.has(taskId)) throw fail(4011);
170
+ const item = (artifacts.items ?? []).find((a) => a.artifactId === artifactId);
171
+ if (!item) throw fail(4404, '产物不存在');
172
+ const body = `# ${item.name}\n\nmock 产物内容(${item.kind})\n`;
173
+ return {
174
+ name: item.name,
175
+ mime: 'text/markdown; charset=utf-8',
176
+ sizeBytes: Buffer.byteLength(body),
177
+ data: Buffer.from(body, 'utf8'),
178
+ };
179
+ },
180
+
181
+ async createTask({ prompt, title, permission = 'requireApproval', budgetMin = 10, attachments } = {}) {
182
+ const taskId = newId('tsk');
183
+ tasks.set(taskId, {
184
+ taskId,
185
+ storedKey: newId('sk'),
186
+ title: title || String(prompt).slice(0, 24),
187
+ status: 'running',
188
+ phase: { index: 1, total: 5, label: '已接收' },
189
+ elapsedSec: 0,
190
+ startedAt: new Date().toISOString(),
191
+ lastActivityAt: new Date().toISOString(),
192
+ hostId: hostInfo.hostId,
193
+ hostName: hostInfo.hostName,
194
+ cwd: '/mock/workspace',
195
+ permission,
196
+ budgetMin,
197
+ needsYou: false,
198
+ pendingTodoCount: 0,
199
+ artifactsCount: 0,
200
+ });
201
+ emit(taskId, 'state', { status: 'running', phase: { index: 1, total: 5, label: '已接收' }, elapsedSec: 0, needsYou: false });
202
+ log(`host createTask ${taskId}`);
203
+ return { ...createOk, taskId, storedKey: tasks.get(taskId).storedKey, acceptedAt: new Date().toISOString() };
204
+ },
205
+
206
+ async appendMessage(taskId, { text, attachments } = {}) {
207
+ if (!tasks.has(taskId)) throw fail(4011);
208
+ const turnId = newId('turn');
209
+ // 纯附件消息 text 可空;mock 只记元数据(不落字节),供端到端断言送达。
210
+ const atts = Array.isArray(attachments) ? attachments : [];
211
+ const names = atts.map((a) => a?.name || a?.kind || 'attachment').join('、');
212
+ const delta = text
213
+ ? `收到:${String(text).slice(0, 40)}`
214
+ : `收到附件:${names || '附件'}`;
215
+ emit(taskId, 'turn', { turnId, type: 'assistant_delta', delta });
216
+ return { ...messageOk, taskId, turnId, acceptedAt: new Date().toISOString() };
217
+ },
218
+
219
+ /**
220
+ * 冷启动历史(FR-CHAT-01):从 emit 落下的宿主形状记录里翻页。
221
+ * 记录按 seq 升序返回;beforeSeq 取更早的一页(seq < beforeSeq)。
222
+ * mock 数据量小,一页装得下,hasMore 恒 false。
223
+ */
224
+ async events(taskId, { beforeSeq, limit = 60 } = {}) {
225
+ if (!tasks.has(taskId)) throw fail(4011);
226
+ const all = history.get(taskId) ?? [];
227
+ const filtered = Number.isFinite(beforeSeq) && beforeSeq > 0
228
+ ? all.filter((r) => r.seq < beforeSeq)
229
+ : all;
230
+ const records = filtered.slice(-Math.min(Math.max(limit, 1), 200));
231
+ return { taskId, records, hasMore: false };
232
+ },
233
+
234
+ async cancelTask(taskId) {
235
+ const t = tasks.get(taskId);
236
+ if (!t) throw fail(4011);
237
+ t.status = 'cancelled';
238
+ emit(taskId, 'state', { status: 'cancelled', phase: { index: 5, total: 5, label: '已停止' }, elapsedSec: t.elapsedSec ?? 0, needsYou: false });
239
+ log(`host cancelTask ${taskId}`);
240
+ return { ...cancelOk, taskId, at: new Date().toISOString() };
241
+ },
242
+
243
+ async answerTodo(taskId, todoId, { decision }) {
244
+ if (!tasks.has(taskId)) throw fail(4011);
245
+ emit(taskId, 'todo', { todoId, state: 'resolved', decision, resolvedAt: new Date().toISOString() });
246
+ return { ...todoOk, taskId, todoId, decision, resolvedAt: new Date().toISOString() };
247
+ },
248
+
249
+ // MARK: 会话动作(与桌面端右键菜单同源;mock 用内存集合模拟 workspaceRegistry)
250
+
251
+ // MARK: 提示词增强(mock 无模型,返回可预期的结构化文本供端到端断言)
252
+
253
+ async enhancePrompt({ text } = {}) {
254
+ const source = String(text ?? '').trim();
255
+ if (!source) throw fail(4400, '待增强的提示词不能为空');
256
+ return {
257
+ text: `目标:\n${source}\n\n要求:\n1. 先给结论,再给依据。\n2. 保留原文给出的数值、路径与名称。\n3. 输出可直接执行的结果,不要额外解释。`,
258
+ provider: 'mock',
259
+ model: 'mock-enhance',
260
+ finishReason: 'stop',
261
+ at: new Date().toISOString(),
262
+ };
263
+ },
264
+
265
+ async pinTask(taskId, { pinned = true } = {}) {
266
+ if (!tasks.has(taskId)) throw fail(4011);
267
+ if (pinned) pinnedIds.add(taskId); else pinnedIds.delete(taskId);
268
+ log(`host ${pinned ? 'pin' : 'unpin'} ${taskId}`);
269
+ return {
270
+ applied: true, taskId, pinned,
271
+ pinnedSessionIds: [...pinnedIds], at: new Date().toISOString(),
272
+ };
273
+ },
274
+
275
+ async archiveTask(taskId, { archived = true, stopActivity = false } = {}) {
276
+ const t = tasks.get(taskId);
277
+ if (!t) throw fail(4011);
278
+ if (archived) {
279
+ // 与宿主一致:运行中会话不带 stopActivity 会拒绝(workspace/session-active → 我们用 4007 表达"忙")。
280
+ if ((t.status === 'running' || t.status === 'pending') && stopActivity !== true) {
281
+ throw fail(4007, '会话正在运行,归档前需先停止', { detail: 'workspace/session-active' });
282
+ }
283
+ if (stopActivity === true && (t.status === 'running' || t.status === 'pending')) {
284
+ t.status = 'cancelled';
285
+ }
286
+ archivedIds.add(taskId);
287
+ pinnedIds.delete(taskId); // 宿主归档时同时取消置顶(client/model.ts installArchived 实证)
288
+ } else {
289
+ archivedIds.delete(taskId);
290
+ }
291
+ log(`host ${archived ? 'archive' : 'unarchive'} ${taskId}`);
292
+ return {
293
+ applied: true, taskId, archived,
294
+ archivedSessionIds: [...archivedIds], at: new Date().toISOString(),
295
+ };
296
+ },
297
+
298
+ async renameTask(taskId, { title } = {}) {
299
+ const t = tasks.get(taskId);
300
+ if (!t) throw fail(4011);
301
+ const name = String(title ?? '').trim();
302
+ if (!name) throw fail(4400, '标题不能为空');
303
+ t.title = name;
304
+ t.lastActivityAt = new Date().toISOString();
305
+ log(`host rename ${taskId} → ${name}`);
306
+ return { applied: true, taskId, title: name, seq: (t.lastSeq ?? 0) + 1, at: new Date().toISOString() };
307
+ },
308
+
309
+ async forkTask(taskId) {
310
+ const t = tasks.get(taskId);
311
+ if (!t) throw fail(4011);
312
+ const forkedTaskId = newId('tsk');
313
+ tasks.set(forkedTaskId, {
314
+ ...t, taskId: forkedTaskId, storedKey: newId('sk'),
315
+ title: `${t.title}(分叉)`,
316
+ status: 'idle', phase: null, startedAt: null, lastActivityAt: new Date().toISOString(),
317
+ needsYou: false, pendingTodoCount: 0,
318
+ });
319
+ log(`host fork ${taskId} → ${forkedTaskId}`);
320
+ return { accepted: true, taskId, forkedTaskId, at: new Date().toISOString() };
321
+ },
322
+
323
+ // MARK: 会话设置同步(与 cordis 适配器同形状;mock 恒 supported,供端到端与回归断言)
324
+
325
+ async sessionSettings(taskId) {
326
+ if (!tasks.has(taskId)) throw fail(4011);
327
+ const selection = modelOf(taskId);
328
+ return {
329
+ taskId,
330
+ permission: {
331
+ supported: true,
332
+ currentValue: tasks.get(taskId).permission ?? 'requireApproval',
333
+ options: MOCK_PERMISSION_OPTIONS,
334
+ },
335
+ model: {
336
+ supported: true,
337
+ current: selection,
338
+ default: { provider: 'deepseek', model: 'deepseek-chat' },
339
+ groups: MOCK_MODEL_GROUPS,
340
+ failures: [],
341
+ },
342
+ serverTime: new Date().toISOString(),
343
+ };
344
+ },
345
+
346
+ async setPermission(taskId, { preset } = {}) {
347
+ if (!tasks.has(taskId)) throw fail(4011);
348
+ const value = String(preset ?? '').trim();
349
+ if (!value) throw fail(4400, 'preset 不能为空');
350
+ if (!MOCK_PERMISSION_OPTIONS.some((o) => o.value === value)) {
351
+ throw fail(4400, `未知权限预设:${value}`);
352
+ }
353
+ tasks.get(taskId).permission = value;
354
+ log(`host setPermission ${taskId} → ${value}`);
355
+ return { applied: true, taskId, value, at: new Date().toISOString() };
356
+ },
357
+
358
+ async selectModel(taskId, { provider, model, reasoningEffort } = {}) {
359
+ if (!tasks.has(taskId)) throw fail(4011);
360
+ const providerId = String(provider ?? '').trim();
361
+ const modelId = String(model ?? '').trim();
362
+ if (!providerId || !modelId) throw fail(4400, 'provider 与 model 不能为空');
363
+ const group = MOCK_MODEL_GROUPS.find((g) => g.id === providerId);
364
+ if (!group || !group.models.some((m) => m.id === modelId)) {
365
+ throw fail(4400, `目录中没有 ${providerId}/${modelId}`);
366
+ }
367
+ const selection = { provider: providerId, model: modelId };
368
+ if (reasoningEffort) selection.reasoningEffort = String(reasoningEffort);
369
+ sessionModels.set(taskId, selection);
370
+ log(`host selectModel ${taskId} → ${providerId}/${modelId}`);
371
+ return { applied: true, taskId, selection, at: new Date().toISOString() };
372
+ },
373
+
374
+ /**
375
+ * 宿主重启钩子(由 GatewayCore.restartHost 调用)。
376
+ *
377
+ * 真实宿主重启后,在跑的任务不会复活,宿主会把它们标成中断。
378
+ * mock 若不建模这一步,列表快照仍报 running,客户端「已中断 · 可续」的降级
379
+ * 会被列表覆盖回「运行中」——端到端就验不出 FR-TASK-06。
380
+ */
381
+ onHostRestart(reason = 'host_restart') {
382
+ let affected = 0;
383
+ for (const t of tasks.values()) {
384
+ if (t.status !== 'running' && t.status !== 'pending') continue;
385
+ t.status = 'interrupted';
386
+ t.needsYou = false;
387
+ t.pendingTodoCount = 0;
388
+ t.lastActivityAt = new Date().toISOString();
389
+ affected += 1;
390
+ // 刻意**不**发事件:调用方紧接着清空环缓冲并断开连接,谁也收不到;
391
+ // 发了只会让「重启那一瞬间」的时序变得不可预测。
392
+ // 状态由随后的列表快照体现——真实宿主也是这样。
393
+ }
394
+ log(`host onHostRestart(${reason}) 降级 ${affected} 个运行中任务`);
395
+ return affected;
396
+ },
397
+
398
+ async diag() {
399
+ return { adapter: 'mock', fixturesDir, tasks: tasks.size };
400
+ },
401
+
402
+ subscribe(fn) {
403
+ subscribers.add(fn);
404
+ return () => subscribers.delete(fn);
405
+ },
406
+
407
+ /** 回放契约里的 10 帧事件流(间隔按 speed 缩放),用于验收"实时"而不只是"首屏" */
408
+ playScenario(taskId = 'tsk_a41f9c', { speed: s = speed } = {}) {
409
+ clearTimers();
410
+ playing = taskId;
411
+ let acc = 0;
412
+ for (const item of scenario.frames || []) {
413
+ acc += (item.delayMs || 60) / s;
414
+ const t = setTimeout(() => {
415
+ timers.delete(t);
416
+ emit(taskId, item.frame.kind, item.frame.data, new Date().toISOString());
417
+ }, acc);
418
+ timers.add(t);
419
+ }
420
+ const done = setTimeout(() => timers.delete(done), acc + 50);
421
+ timers.add(done);
422
+ log(`host playScenario ${taskId} frames=${(scenario.frames || []).length}`);
423
+ return { playing, frames: (scenario.frames || []).length };
424
+ },
425
+
426
+ stopScenario: clearTimers,
427
+ isPlaying: () => playing,
428
+
429
+ async close() {
430
+ clearTimers();
431
+ subscribers.clear();
432
+ },
433
+ };
434
+
435
+ if (autoPlay) setTimeout(() => host.playScenario(), 50).unref?.();
436
+ return host;
437
+ }
@@ -0,0 +1,99 @@
1
+ // adapter/mux-host.mjs — HTTP 探测式宿主适配器(X2 考古后降级为诊断用途)
2
+ // 纪律(ADR-12):这一层是唯一允许出现宿主 API 的地方。
3
+ //
4
+ // X2 结论(2026-11-16,见 RUNBOOK §10):宿主不存在 `/api/remote.mux` HTTP 端点
5
+ // (asar 内 mux 命中全是 tmux-context);宿主的「mux」是 Gateway 的
6
+ // RemoteStreamMuxServer——Typert RPC 挂在 webServer 的 WebSocket `/api` 上。
7
+ // 进程内路径由 cordis-host.mjs 承担;本适配器仅保留 probe 诊断能力,
8
+ // 任何业务方法都显式抛 4021,绝不假装成功——
9
+ // 假成功比连不上更糟:它会让客户端在错误的前提下通过验收。
10
+
11
+ import { fail } from '../protocol.mjs';
12
+
13
+ const DEFAULT_BASE = 'http://127.0.0.1:3000';
14
+
15
+ export function createMuxHost({ baseUrl = DEFAULT_BASE, token, log = () => {}, timeoutMs = 2500 } = {}) {
16
+ const root = baseUrl.replace(/\/+$/, '');
17
+ let cachedInfo = null;
18
+ let lastProbe = null;
19
+
20
+ const authHeaders = token ? { authorization: `Bearer ${token}` } : {};
21
+
22
+ async function probe() {
23
+ const startedAt = Date.now();
24
+ const url = `${root}/api/remote.mux`;
25
+ try {
26
+ const ctrl = new AbortController();
27
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
28
+ const res = await fetch(url, { method: 'GET', headers: authHeaders, signal: ctrl.signal });
29
+ clearTimeout(timer);
30
+ const text = await res.text();
31
+ lastProbe = {
32
+ ok: res.ok,
33
+ status: res.status,
34
+ ms: Date.now() - startedAt,
35
+ url,
36
+ bodyPreview: text.slice(0, 200),
37
+ };
38
+ if (res.ok) {
39
+ try {
40
+ const body = JSON.parse(text);
41
+ cachedInfo = normalizeInfo(body);
42
+ } catch {
43
+ /* 返回非 JSON 也接受:说明端点存在,但报文格式未确认 */
44
+ }
45
+ }
46
+ return lastProbe;
47
+ } catch (err) {
48
+ lastProbe = { ok: false, status: 0, ms: Date.now() - startedAt, url, error: err.message };
49
+ return lastProbe;
50
+ }
51
+ }
52
+
53
+ function normalizeInfo(body = {}) {
54
+ return {
55
+ hostId: body.hostId || 'host_unknown',
56
+ hostName: body.hostName || body.name || 'DSH 宿主',
57
+ hostVersion: body.hostVersion || body.version || 'unknown',
58
+ platform: body.platform || process.platform,
59
+ protocolVersion: '1.0',
60
+ caps: Array.isArray(body.caps) ? body.caps : [],
61
+ maxConcurrentTasks: body.maxConcurrentTasks ?? 3,
62
+ };
63
+ }
64
+
65
+ const notMapped = (method) =>
66
+ fail(4021, `方法 ${method} 尚未与 /api/remote.mux 对齐(X2 未闭环)`, {
67
+ detail: lastProbe ? `probe status=${lastProbe.status}` : '尚未探测',
68
+ });
69
+
70
+ const host = {
71
+ kind: 'mux',
72
+ info() {
73
+ if (!cachedInfo) {
74
+ throw fail(4021, '宿主信息尚未取得:/api/remote.mux 不可达或格式未确认', {
75
+ detail: lastProbe ? `status=${lastProbe.status} url=${lastProbe.url}` : '尚未探测',
76
+ });
77
+ }
78
+ return cachedInfo;
79
+ },
80
+ probe,
81
+ lastProbe: () => lastProbe,
82
+ listTasks: async () => notMapped('tasks.list'),
83
+ getTask: async () => notMapped('tasks.get'),
84
+ listArtifacts: async () => notMapped('artifacts.list'),
85
+ createTask: async () => notMapped('tasks.create'),
86
+ appendMessage: async () => notMapped('tasks.message'),
87
+ cancelTask: async () => notMapped('tasks.cancel'),
88
+ answerTodo: async () => notMapped('todos.answer'),
89
+ diag: async () => ({ adapter: 'mux', probe: lastProbe }),
90
+ subscribe(fn) {
91
+ // 真实宿主的事件流要挂 mux 的推送通道;未接通前不产生任何事件
92
+ log('mux subscribe:事件通道未接通(等 X2 方法表)');
93
+ return () => fn;
94
+ },
95
+ async close() {},
96
+ };
97
+
98
+ return host;
99
+ }