@luchenglong/cli-bridge 0.2.6 → 0.2.8

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,618 +1,517 @@
1
- // providers/mimo.mjs — mimo provider descriptor(单后端:本地 mimo CLI / MiMoCode)。
2
- //
3
- // 移植基线:mimo-first-bridge v1.x 仓 core/mimo-core.mjs + core/runtime-settings.mjs +
4
- // preset/mimo-first/mimo-first-bridge.mjs 的内联逻辑(buildArgv / parseMimoJson /
5
- // buildResult / 三工具 schema / mimo_settings),语义逐字保持;与 provider 无关的骨架
6
- // (状态引擎/行流/回退弹窗/展示层/超时护栏)在 core/bridge-kit.mjs(契约 §1)。
7
- //
8
- // 2026-10 去 desktop 化(用户定案:MiMo 免费 API 服务已被官方终止 + 本机 0 凭据):
9
- // 1. 取消 mimo-desktop 后端 —— 只走 `mimo run`(MiMoCode CLI,官方便携安装位置
10
- // ~/.mimocode/bin/mimo.exe);登录由用户在 CLI 侧 `mimo auth login` 自理。
11
- // 2. 模型由用户在设置里手动指定(settings.defaultModel,不写死默认值);留空 =
12
- // 不传 --model,交给 mimo CLI 自身默认。可用模型以 `mimo models` 实测为准
13
- // (xiaomi/mimo-v2.6-flash / -pro / -pro-ultraspeed 等)。
14
- // 3. 是否启用 mimo 由调度(_scheduling.enabled)控制;本描述符不含任何开关。
15
- //
16
- // 红线(PROVIDER-CONTRACT.md §8 + Lead 定案):本文件会被 build 内联进 dynamic 沙箱
17
- // (new Function)—— 绝不出现 import.meta 字面量;process/fs/child_process 只经
18
- // globalThis.process.getBuiltinModule + typeof 守卫读取;只允许 import bridge-kit。
19
- import { createStatusEngine, createRunner, clampInt, shortLabel, summarizeArgs } from '../core/bridge-kit.mjs'
20
-
21
- // ── 单后端归一(旧 mimo-core 双后端 verbatim 的收缩形态)───────────────────────
22
- // mimo-desktop 取消后不再有第二后端:backends() 恒 null;任何输入(含历史别名
23
- // mimocode / mimo-cli / desktop / 空串 / 非法值)一律归一为 null。会话路由由
24
- // engine.resolveTarget(cwd + sessionId)完成,backend 恒 null。
25
- const DEFAULT_TIMEOUT_SEC = 600
26
-
27
- // 旧 LIMIT_RE(比 kit 版多 free-API/登录/第三方等 MiMo 文案;provider.isLimited 覆盖)。
28
- // 命名 MIMO_ 前缀:dynamic 内联时 kit 也声明顶层 LIMIT_RE,同名会在同一脚本作用域
29
- // 触发「Identifier already declared」构建错误(scripts/build.mjs 文本拼接的固有约束)。
30
- const MIMO_LIMIT_RE = /rate.?limit|ratelimit|429|too many|quota|insufficient|credit|balance|exhausted|exceed|network|offline|ENETUNREACH|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|timeout|timed out|unavailable|503|502|500|401|403|unauthorized|invalid api|api key|connection|proxy|socket|tls|ssl|dns|free API service has ended|sign in|configure a third-party|网络|超时|限流|流量|受限|配额|金额|余额|额度|认证|连接|断开|登录|第三方/i
31
-
32
- // ── Node 内建探测(沙箱纪律:getBuiltinModule + typeof 守卫)───────────────────
33
- // 名字带 mimo 前缀:本文件会与 bridge-kit / core/scheduling.mjs【文本内联进同一个动态
34
- // 沙箱脚本作用域】,撞名即「Identifier already declared」构建错误。
35
- function mimoBuiltin(name) {
36
- try {
37
- const proc = globalThis.process
38
- return (proc && typeof proc.getBuiltinModule === 'function') ? proc.getBuiltinModule(name) : null
39
- } catch (e) { return null }
40
- }
41
-
42
- // ── 可执行文件解析(env MIMO_BIN/MIMO_CLI > 已知安装位置 > PATH 名字)───────────
43
- // MiMoCode CLI 官方便携安装目录:<USERPROFILE|HOME>/.mimocode/bin/mimo[.exe]。
44
- // 沙箱内可能没有 fs —— 全部读取走 typeof 守卫,读不到就返回空数组(退回 PATH 查找)。
45
- const MIMO_EXE_DIR = ['.mimocode', 'bin']
46
-
47
- /** 探测本机 mimo 可执行文件候选路径(官方便携安装位置);无 fs 能力时返回空数组。 */
48
- export function mimoCandidateExePaths(env) {
49
- const e = env || {}
50
- const out = []
51
- const fs = mimoBuiltin('node:fs')
52
- if (!fs || typeof fs.existsSync !== 'function') return out
53
- const path = mimoBuiltin('node:path')
54
- const join = (path && typeof path.join === 'function') ? ((a, b) => path.join(a, b)) : ((a, b) => a + '/' + b)
55
- for (const k of ['USERPROFILE', 'HOME']) {
56
- if (!e[k]) continue
57
- const dir = join(join(String(e[k]), MIMO_EXE_DIR[0]), MIMO_EXE_DIR[1])
58
- for (const base of ['mimo.exe', 'mimo']) {
59
- const exe = join(dir, base)
60
- try { if (fs.existsSync(exe) && out.indexOf(exe) < 0) out.push(exe) } catch (err) { /* 探测失败静默跳过 */ }
61
- }
62
- }
63
- return out
64
- }
65
-
66
- /**
67
- * 解析本次调用使用的 exe 前缀(数组或字符串)。
68
- * 优先级:binPath(显式路径)> env MIMO_BIN/MIMO_CLI > 已知安装位置 > PATH 名字。
69
- */
70
- export function resolveMimoExePrefix(env, binPath) {
71
- const e = env || {}
72
- const bin = binPath || e.MIMO_BIN || e.MIMO_CLI || ''
73
- if (bin) {
74
- if (/\.(mjs|cjs|js)$/i.test(bin)) {
75
- const proc = globalThis.process
76
- return [(proc && proc.execPath) ? proc.execPath : 'node', bin]
77
- }
78
- return [String(bin)]
79
- }
80
- const found = mimoCandidateExePaths(e)
81
- return found.length ? [found[0]] : ['mimo']
82
- }
83
-
84
- // ── 模型列表(`mimo models`;设置面板下拉用)───────────────────────────────────
85
- // 实测输出形如每行 `provider/model — window 1M, compacts at 900K`(分隔符是中文破折号
86
- // U+2014)。模型名自身含连字符(xiaomi/mimo-v2.6-pro-ultraspeed),所以只认「行首的
87
- // provider/model」,其后一律当描述文本;表头/说明/空行一律丢弃,绝不抛。
88
- const MIMO_MODEL_ID_RE = /^([A-Za-z0-9_.-]+\/[A-Za-z0-9_.@#+-]+)(?=$|[\s—–:|,])/
89
-
90
- /** 解析 `mimo models` 文本输出为 [{id, provider, name, note}](去重、保序)。 */
91
- export function parseMimoModels(text) {
92
- const out = []
93
- const seen = Object.create(null)
94
- for (const raw of String(text || '').split(/\r?\n/)) {
95
- // 去掉列表记号(• * - 1. 等)与行首空白,避免把记号当 provider 名。
96
- const ln = raw.replace(/^[^A-Za-z0-9]+/, '').trim()
97
- if (!ln) continue
98
- const m = ln.match(MIMO_MODEL_ID_RE)
99
- if (!m) continue
100
- const id = m[1]
101
- if (seen[id]) continue
102
- seen[id] = true
103
- const slash = id.indexOf('/')
104
- out.push({ id: id, provider: id.slice(0, slash), name: id.slice(slash + 1), note: ln.slice(id.length).replace(/^[\s—–:|,-]+/, '').trim() })
105
- }
106
- return out
107
- }
108
-
109
- /**
110
- * 同步抓取模型列表(供设置面板下拉)。失败返回空数组 —— 下拉退化为自由输入,
111
- * 绝不因探测失败影响面板渲染。仅 spawnSync 可用时生效(宿主形态)。
112
- */
113
- export function fetchMimoModelsSync(env, timeoutMs) {
114
- try {
115
- const child = mimoBuiltin('node:child_process')
116
- if (!child || typeof child.spawnSync !== 'function') return []
117
- const prefix = resolveMimoExePrefix(env)
118
- const r = child.spawnSync(prefix[0], prefix.slice(1).concat(['models']), { encoding: 'utf8', timeout: clampInt(timeoutMs, 8000, 1000, 30000), windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
119
- if (!r || r.error || r.status !== 0) return []
120
- return parseMimoModels(String(r.stdout || ''))
121
- } catch (e) { return [] }
122
- }
123
-
124
- // ── 三工具 schema(旧 preset verbatim;desktop 专属入参已随之后端取消而删除)────
125
- const MODEL_DESC = 'provider/model 格式,如 xiaomi/mimo-v2.6-flash;留空用设置里的默认模型'
126
- const RUN_PARAMS = {
127
- type: 'object', additionalProperties: true, required: ['prompt'],
128
- properties: {
129
- prompt: { type: 'string', description: 'The task instruction for mimo. On first dispatch for a topic, include a compact CONTEXT preamble (goal, repo root, key paths, decisions/constraints; point at paths, do not paste file contents — mimo reads the repo itself). For follow-ups on the same topic, use mimo_continue with latest=true or sessionId (mimo keeps conversation context; state only what is new).' },
130
- mode: { type: 'string', enum: ['auto', 'plan', 'build', 'compose', 'accept-edits'], description: 'auto follows DSH plan state (plan vs build); plan = read-only analysis (--agent plan); build = full tools (--agent build); compose = compose workflow.' },
131
- model: { type: 'string', description: MODEL_DESC },
132
- effort: { type: 'string', enum: ['low', 'medium', 'high'], description: 'Optional reasoning effort, mapped to mimo --variant (low→minimal, high→high).' },
133
- cwd: { type: 'string', description: 'Working directory for mimo (--dir).' },
134
- timeoutSec: { type: 'integer', description: 'Hard timeout seconds (10-3600, default 600). Grace +60s on top.' },
135
- background: { type: 'boolean', description: 'Defaults to true: dispatch returns a jobId immediately; collect with job_output, watch progress with mimo_status. Set false to block for the final answer.' },
136
- sessionId: { type: 'string', description: 'Optional mimo session id to resume (--session). Follow-ups on the same topic normally go through mimo_continue.' },
137
- title: { type: 'string', description: 'Optional session title.' }
138
- }
139
- }
140
- const CONTINUE_PARAMS = {
141
- type: 'object', additionalProperties: true, required: ['prompt'],
142
- properties: {
143
- prompt: { type: 'string', description: 'Follow-up instruction for the ongoing mimo session. State only what is new; mimo preserves its conversation context.' },
144
- sessionId: { type: 'string', description: 'mimo session id to resume (--session).' },
145
- latest: { type: 'boolean', description: 'Continue the most recent mimo session (--continue).' },
146
- mode: { type: 'string', enum: ['auto', 'plan', 'build', 'compose', 'accept-edits'], description: 'Execution mode.' },
147
- model: { type: 'string', description: MODEL_DESC },
148
- effort: { type: 'string', enum: ['low', 'medium', 'high'], description: 'Optional reasoning effort.' },
149
- cwd: { type: 'string', description: 'Working directory for mimo.' },
150
- timeoutSec: { type: 'integer', description: 'Hard timeout seconds (10-3600, default 600).' },
151
- background: { type: 'boolean', description: 'Defaults to true (background job).' }
152
- }
153
- }
154
- const STATUS_PARAMS = { type: 'object', additionalProperties: true, required: [], properties: { cwd: { type: 'string', description: 'Optional: filter the snapshot to a single project (working directory).' } } }
155
- const SETTINGS_PARAMS = { type: 'object', additionalProperties: true, required: [], properties: { model: { type: 'string', description: MODEL_DESC } } }
156
- const SETTINGS_DESCRIPTION = 'Read or change the default mimo model (settings). Call with model=<provider/model> to save it as the default for subsequent mimo_run/mimo_continue; call with no args to read current settings. Persisted to the settings file; a per-call `model` argument on mimo_run/mimo_continue overrides it for that call only. Available models are listed by `mimo models` on this machine (mimo CLI must be installed and logged in).'
157
-
158
- function renderSettings(value) {
159
- const s = value || {}
160
- const lines = [
161
- 'mimo settings',
162
- ' settings file : ' + (s.settingsPath || '(unknown)'),
163
- ' default model : ' + (s.defaultModel || '(unset — 不传 --model)'),
164
- ' effective : ' + (s.effective || '(unknown)'),
165
- ' exe : ' + (s.exe || '(unknown)'),
166
- ' saved : ' + (s.saved ? 'yes' : 'no')
167
- ]
168
- if (s.saveError) lines.push(' save error : ' + s.saveError)
169
- if (s.note) lines.push(' note : ' + s.note)
170
- return [{ type: 'text', text: lines.join('\n') }]
171
- }
172
- // ── 可纯函数化的 mimo-core 语义(descriptor 方法 + 独立导出双份)───────────────
173
- function parseMimoJson(stdoutText) {
174
- const trimmed = String(stdoutText || '').trim()
175
- if (!trimmed) return null
176
- const events = []
177
- const lines = trimmed.split(/\r?\n/)
178
- for (const raw of lines) {
179
- const ln = raw.trim()
180
- if (!ln.startsWith('{')) continue
181
- try {
182
- const obj = JSON.parse(ln)
183
- if (obj && typeof obj === 'object') events.push(obj)
184
- } catch (e) { /* tolerate log lines */ }
185
- }
186
- if (!events.length) {
187
- try {
188
- const obj = JSON.parse(trimmed)
189
- if (obj && typeof obj === 'object') events.push(obj)
190
- } catch (e) {
191
- return { events: [], text: trimmed, sessionId: null, error: null, steps: [] }
192
- }
193
- }
194
- let sessionId = null
195
- let text = ''
196
- let errorMessage = null
197
- let errorName = null
198
- let numTurns = 0
199
- let totalTokens = null
200
- const steps = []
201
- const textParts = []
202
- for (const ev of events) {
203
- if (ev.sessionID && typeof ev.sessionID === 'string') sessionId = ev.sessionID
204
- if (ev.sessionId && typeof ev.sessionId === 'string') sessionId = ev.sessionId
205
- if (ev.session && typeof ev.session === 'object' && ev.session.id) sessionId = ev.session.id
206
- if (ev.type === 'session' && ev.properties && ev.properties.id) sessionId = ev.properties.id
207
- const t = ev.type
208
- const p = ev.properties || ev
209
- if (t === 'error') {
210
- const err = ev.error || p
211
- errorMessage = (err.data && err.data.message) || err.message || err.name || 'error'
212
- errorName = err.name || 'Error'
213
- } else if (t === 'text' || t === 'message' || t === 'assistant' || t === 'output') {
214
- const chunk = p.text || p.content || p.message || p.output || (typeof ev.text === 'string' ? ev.text : '')
215
- if (typeof chunk === 'string' && chunk) {
216
- textParts.push(chunk)
217
- steps.push({ at: Date.now(), kind: 'text', label: shortLabel(chunk) })
218
- }
219
- } else if (t === 'step-start' || t === 'step-finish' || t === 'step_update') {
220
- numTurns += 1
221
- if (p.tokens && typeof p.tokens === 'object') {
222
- const tt = p.tokens.total ?? p.tokens.input ?? p.tokens.output
223
- if (typeof tt === 'number') totalTokens = (totalTokens || 0) + tt
224
- }
225
- if (t === 'step_update') {
226
- const name = p.tool_name || p.tool || p.name
227
- if (name) steps.push({ at: Date.now(), kind: 'tool', label: shortLabel(name + ' ' + JSON.stringify(summarizeArgs(p.arguments || p.args || p.input) || {})) })
228
- }
229
- } else if (t === 'tool' || t === 'tool-call' || t === 'tool_use') {
230
- const name = p.tool || p.name || p.tool_name || 'tool'
231
- steps.push({ at: Date.now(), kind: 'tool', label: shortLabel(name + ' ' + JSON.stringify(summarizeArgs(p.arguments || p.args || p.input) || {})) })
232
- }
233
- }
234
- if (textParts.length) text = textParts.join('\n')
235
- else {
236
- const last = events[events.length - 1] || {}
237
- const r = last.result || last
238
- if (typeof r.response === 'string') text = r.response
239
- else if (typeof r.text === 'string') text = r.text
240
- }
241
- return { events, text, sessionId, error: errorMessage, errorName, numTurns, totalTokens, steps }
242
- }
243
-
244
- function buildResult(parsed, outcome, mode, stderrText, stdoutText, backend) {
245
- const MAX_TRAIL = 12
246
- const exitCode = outcome ? outcome.exitCode : null
247
- const errText = (parsed && parsed.error) ? String(parsed.error) : ''
248
- const stderr = (stderrText ? String(stderrText).slice(-2000) : '') + (errText ? (stderrText ? ' ' : '') + errText : '')
249
- const text = parsed && typeof parsed.text === 'string' ? parsed.text : ''
250
- const failed = exitCode !== 0 || !!(parsed && parsed.error)
251
- const be = (parsed && parsed.backend) || (outcome && outcome.backend) || backend || null
252
- if (parsed) {
253
- return {
254
- ok: !failed && (!!text || parsed.accepted === true),
255
- status: failed ? (parsed.errorName || 'ERROR') : (parsed.accepted && !text ? 'ACCEPTED' : (text ? 'SUCCESS' : 'EMPTY')),
256
- response: text,
257
- sessionId: parsed.sessionId || null,
258
- durationSeconds: null,
259
- numTurns: parsed.numTurns || null,
260
- totalTokens: parsed.totalTokens || null,
261
- exitCode, mode, backend: be,
262
- stderr,
263
- errorMessage: parsed.error || '',
264
- accepted: parsed.accepted === true,
265
- steps: Array.isArray(parsed.steps) ? parsed.steps.slice(-MAX_TRAIL) : []
266
- }
267
- }
268
- return {
269
- ok: false, status: 'PARSE_ERROR', response: '', sessionId: null,
270
- durationSeconds: null, numTurns: null, totalTokens: null,
271
- exitCode, mode, backend: be, stderr, errorMessage: '',
272
- rawStdout: String(stdoutText || '').slice(-2000)
273
- }
274
- }
275
-
276
- export default function defineProvider(deps = {}) {
277
- const env = deps.env || {}
278
- const nodeFs = deps.nodeFs || null
279
- const nodePath = deps.nodePath || null
280
- let host = null // attach 后保存 hostOpts(preset/dynamic 形态提供 getSettings)
281
- let settingsRef = { defaultModel: '' }
282
-
283
- /** 取当前生效的偏好设置。三条来源按优先级合并,每次 buildArgv 都重新读 ——
284
- * 面板改默认模型后无需重启即生效:
285
- * 1) `host.getSettings('mimo')` —— preset/dynamic 形态(attach 时由宿主注入);
286
- * 2) `deps.readSettings()` —— MCP 形态(真 Node 进程,每次现读设置文件);
287
- * 3) `settingsRef` —— attach 时固化的一次性快照 / 缺省值。
288
- * 三条都拿不到 → 缺省 `{defaultModel:''}`(= 不传 --model,交给 mimo CLI 自决)。
289
- *
290
- * 历史坑:MCP 形态不 attach(自建 engine),只认 host.getSettings 会让面板设置的
291
- * defaultModel 在 MCP 面对 mimo_run 完全失效 —— 只有 args.model 才落地。
292
- * 三个形态行为不一致是缺陷,故此处统一把 readSettings 纳入。 */
293
- function currentSettings() {
294
- const out = Object.assign({}, settingsRef)
295
- try {
296
- if (typeof deps.readSettings === 'function') {
297
- const r = deps.readSettings()
298
- if (r && typeof r === 'object') {
299
- // 宿主可返回 { partition, path, home } 或直接返回分区对象(宽松兼容)。
300
- const part = ('partition' in r || 'path' in r || 'home' in r) ? r.partition : r
301
- if (part && typeof part === 'object') Object.assign(out, part)
302
- }
303
- }
304
- } catch (e) { }
305
- try {
306
- if (host && typeof host.getSettings === 'function') {
307
- const s = host.getSettings('mimo')
308
- if (s && typeof s === 'object') Object.assign(out, s)
309
- }
310
- } catch (e) { }
311
- return out
312
- }
313
-
314
- // 模型优先级:调用参数 > 宿主注入设置 > runner opts 透传 > 空(不传 --model)。
315
- // 用户要求「不设默认 → 由 mimo CLI 自决」,故空值绝不落地 --model。
316
- function effectiveModel(args, opts) {
317
- const o = opts || {}
318
- const fromArg = (args && args.model && String(args.model).trim()) || ''
319
- if (fromArg) return fromArg
320
- const fromSettings = (currentSettings().defaultModel || '').trim()
321
- if (fromSettings) return fromSettings
322
- const fromOpts = (o.settings && o.settings.defaultModel) || o.defaultModel
323
- return fromOpts ? String(fromOpts).trim() : ''
324
- }
325
-
326
- // ── 统一设置分区读取(keystone 落盘;descriptor 只读)。宿主注入 deps.readSettings
327
- // 动态读取(preset/MCP 每次取最新文件值),或静态 deps.settings(测试/dynamic)。
328
- function liveSettings() {
329
- if (typeof deps.readSettings === 'function') {
330
- try {
331
- const r = deps.readSettings()
332
- if (r && typeof r === 'object') {
333
- // 宿主可返回 { partition, path, home } 或直接返回分区对象(宽松兼容)。
334
- if ('partition' in r || 'path' in r || 'home' in r) {
335
- return { partition: r.partition || null, path: r.path || null, home: r.home || null }
336
- }
337
- return { partition: r, path: deps.settingsPath || null, home: deps.dshHome || null }
338
- }
339
- } catch (e) { }
340
- }
341
- return { partition: (deps.settings && typeof deps.settings === 'object') ? deps.settings : null, path: deps.settingsPath || null, home: deps.dshHome || null }
342
- }
343
-
344
- const descriptor = {
345
- id: 'mimo', label: 'MIMO', presetId: 'cordis-mimo', defaultBackend: null, defaultMode: 'auto',
346
- exeName: 'mimo', binEnvVars: ['MIMO_BIN', 'MIMO_CLI'], unavailableStatus: 'MIMO_UNAVAILABLE',
347
-
348
- // 单后端:backends() 恒 null;历史别名(mimocode/mimo-cli/desktop)与非法值一律
349
- // 归一为 null(契约 §1:非法输入返回 null)。
350
- backends() { return null },
351
- normalizeBackend() { return null },
352
- resolveBackend(args, target, preferred) { return null },
353
-
354
- // 旧 preset buildArgv(exe, args, planActive) verbatim 语义(execPrefix 可为
355
- // [nodeExe, binPath] 数组,runner 已归一)。
356
- buildArgv(exePrefix, args, opts) {
357
- const o = opts || {}
358
- const timeoutSec = clampInt(args.timeoutSec, DEFAULT_TIMEOUT_SEC, 10, 3600)
359
- const argv = Array.isArray(exePrefix) ? exePrefix.slice() : [String(exePrefix)]
360
- argv.push('run')
361
- if (args.prompt != null && String(args.prompt).length) argv.push(String(args.prompt))
362
- argv.push('--format', 'json', '--dangerously-skip-permissions')
363
- let mode = args.mode || o.defaultMode || 'auto'
364
- if (mode === 'auto') mode = o.planActive ? 'plan' : 'build'
365
- if (mode === 'accept-edits') mode = 'build'
366
- // mimo --agent: build | plan | compose
367
- const agent = args.agent || mode
368
- if (agent === 'plan' || agent === 'build' || agent === 'compose') argv.push('--agent', agent)
369
- // 模型:调用参数 > 设置 defaultModel > 不传(mimo CLI 自身默认)。
370
- const model = effectiveModel(args, o)
371
- if (model) argv.push('--model', String(model))
372
- // effort (low/medium/high) maps to mimo --variant; pass-through if already a variant name
373
- let variant = args.variant || args.effort
374
- if (variant === 'low') variant = 'minimal'
375
- else if (variant === 'medium') variant = undefined
376
- else if (variant === 'high') variant = 'high'
377
- if (variant) argv.push('--variant', String(variant))
378
- if (args.cwd) argv.push('--dir', String(args.cwd))
379
- if (args.sessionId) argv.push('--session', String(args.sessionId))
380
- else if (args.continueLatest) argv.push('--continue')
381
- if (args.title) argv.push('--title', String(args.title))
382
- return { argv, timeoutSec, mode: agent }
383
- },
384
-
385
- parseJson: parseMimoJson,
386
- buildResult,
387
-
388
- // 旧 foldStepUpdate 语义 verbatim(识别 tool/text/error 事件),trail 条目同时带
389
- // kit 展示层字段(stepIndex/tool/state/args)与旧字段(kind/label),这样
390
- // renderStatus 与 MCP 快照映射(buildMcpBridgePayload)都能直接渲染。
391
- foldStreamEvent(ev, p, summarizeArgsFn, maxArgLen, maxTrail) {
392
- if (!ev || typeof ev !== 'object') return
393
- const t = ev.type
394
- const pr = ev.properties || ev
395
- const cap = maxTrail || 12
396
- const idx = p.trail ? p.trail.length : 0
397
- let entry = null
398
- if (t === 'tool' || t === 'tool-call' || t === 'tool_use' || t === 'step_update') {
399
- const name = pr.tool_name || pr.tool || pr.name
400
- if (name) {
401
- const args = (summarizeArgsFn || summarizeArgs)(pr.arguments || pr.args || pr.input) || null
402
- const state = pr.state || pr.status || 'ACTIVE'
403
- entry = {
404
- at: Date.now(), kind: 'tool', stepIndex: idx, tool: String(name), args, state,
405
- label: shortLabel(name + ' ' + JSON.stringify(args || {}))
406
- }
407
- if (state === 'ACTIVE') p.current = { tool: String(name), args, stepIndex: idx, since: entry.at }
408
- else if (p.current && p.current.tool === String(name) && p.current.stepIndex === idx) p.current = null
409
- }
410
- } else if (t === 'text' || t === 'message') {
411
- const chunk = pr.text || pr.content || ''
412
- if (typeof chunk === 'string' && chunk) {
413
- const capLen = maxArgLen || 120
414
- entry = { at: Date.now(), kind: 'text', stepIndex: idx, tool: 'agent_response', args: { text: chunk.slice(0, capLen) }, state: 'ACTIVE', label: shortLabel(chunk) }
415
- p.current = { tool: 'agent_response', args: entry.args, stepIndex: idx, since: entry.at }
416
- }
417
- } else if (t === 'error') {
418
- const err = pr.error || pr
419
- const msg = (err.data && err.data.message) || err.message || 'error'
420
- entry = { at: Date.now(), kind: 'error', stepIndex: idx, tool: 'error', args: { message: String(msg).slice(0, maxArgLen || 120) }, state: 'FAILED', label: shortLabel(msg) }
421
- }
422
- if (entry && p.trail) {
423
- p.trail.push(entry)
424
- while (p.trail.length > cap) p.trail.shift()
425
- }
426
- },
427
-
428
- // 旧 LIMIT_RE 覆盖(kit 版不含 free API/登录/第三方等 MiMo 文案)。
429
- isLimited(res) {
430
- if (!res || res.ok) return false
431
- if (res.status === 'SPAWN_ERROR' || res.status === 'MIMO_UNAVAILABLE' || res.status === 'HUNG_TIMEOUT') return true
432
- const hay = String(res.stderr || '') + ' ' + String(res.response || '') + ' ' + String(res.status || '') + ' ' + String(res.errorMessage || '')
433
- return MIMO_LIMIT_RE.test(hay)
434
- },
435
-
436
- failureHint(res) {
437
- if (!res || res.ok) return ''
438
- const st = String(res.status || '')
439
- if (st === 'MIMO_UNAVAILABLE') return '[诊断] 未找到 mimo 可执行文件:请安装 MiMoCode CLI(mimo,官方便携安装位置 ~/.mimocode/bin/mimo.exe),或设置 MIMO_BIN 指向其绝对路径。'
440
- const hay = String(res.stderr || '') + ' ' + String(res.errorMessage || '') + ' ' + String(res.response || '')
441
- if (/free API service has ended|sign in|configure a third-party|登录|第三方|免费/i.test(hay)) {
442
- return '[诊断] MiMo 免费 API 已终止,请在 mimo CLI 用 `mimo auth login` 登录或配置第三方 API,并在 CLI Bridge 设置里指定模型。'
443
- }
444
- if (/model not found|unknown model|no models available|invalid model|unknown provider/i.test(hay)) {
445
- return '[诊断] mimo 模型不可用或模型名无效:先在本机运行 `mimo models` 列出可用模型,再把 provider/model 填进 CLI Bridge 的「默认模型」设置(或本次调用的 model 参数)。'
446
- }
447
- return ''
448
- },
449
-
450
- // ACCEPTED 计入成功态(指示灯不红;契约 §1);desktop 取消后不再产生 ACCEPTED,
451
- // 但成功态集合逐字保持不变(兼容旧会话/测试语义)。
452
- isSuccessStatus(st) {
453
- if (!st) return false
454
- return st === 'SUCCESS' || st === 'ACCEPTED'
455
- },
456
-
457
- tools: {
458
- run: { name: 'mimo_run', description: 'Dispatch a coding/build/debug/investigation task to the local mimo agent CLI (Xiaomi MiMoCode) and return its final answer. DSH fully controls mimo (--dangerously-skip-permissions; mimo never prompts). On rate-limit/network failure DSH pops a fallback dialog; fallback=true means finish with native tools. Runs in the background by default (returns a jobId immediately; collect with job_output); set background=false to block for the final answer. While it runs, call mimo_status to watch what mimo is doing live.', inputSchema: RUN_PARAMS },
459
- continue: { name: 'mimo_continue', description: 'Continue an existing mimo session with a follow-up prompt. Pass sessionId or set latest=true. Same DSH-controlled, no-prompt execution and same fallback dialog as mimo_run.', inputSchema: CONTINUE_PARAMS },
460
- status: { name: 'mimo_status', description: 'Read a live snapshot of what the local mimo agent is currently doing. Returns one section per project (working directory): running count, current step, recent step trail, last completed run status + session id, per-project runs/token usage. Call this to check on an in-flight mimo_run/mimo_continue without waiting for it to finish.', inputSchema: STATUS_PARAMS }
461
- },
462
-
463
- // mimo_settings:入参键保持旧 prompt 连续性(backend/desktopModel → model),落统一
464
- // 分区 defaultModel(迁移映射 keystone 已做)。写盘仅在宿主注入 nodeFs + nodePath 时
465
- // 可用;否则回显(dynamic 沙箱旧 echo 语义)。
466
- extraTools: [{
467
- name: 'mimo_settings',
468
- description: SETTINGS_DESCRIPTION,
469
- inputSchema: SETTINGS_PARAMS,
470
- render: renderSettings,
471
- async logic(args) {
472
- const a = args || {}
473
- const live = liveSettings()
474
- const cur = Object.assign({ defaultModel: '' }, live.partition || {})
475
- let settingsPath = live.path || null
476
- let saved = false, saveError = null
477
- const home = live.home || deps.dshHome || null
478
- const patch = (typeof a.model === 'string' && a.model.trim()) ? { defaultModel: a.model.trim() } : null
479
- if (patch && nodeFs && nodePath && (settingsPath || home)) {
480
- try { settingsPath = await writePartition(nodeFs, nodePath, settingsPath, home, env, cur, patch); saved = true } catch (e) { saveError = String(e && e.message || e) }
481
- }
482
- const merged = Object.assign({}, cur)
483
- if (patch) merged.defaultModel = patch.defaultModel
484
- return {
485
- ok: !saveError,
486
- settingsPath: settingsPath || '(unified; not writable in this host)',
487
- defaultModel: merged.defaultModel || '',
488
- effective: merged.defaultModel ? ('settings:' + merged.defaultModel) : '(unset — 不传 --model,mimo CLI 自决)',
489
- exe: resolveMimoExePrefix(env).join(' '),
490
- saved, saveError,
491
- note: '默认模型在设置面板或本工具里指定(provider/model);mimo_run/mimo_continue 的 model 参数可单次覆盖。可用模型:在本机运行 `mimo models` 查看。'
492
- }
493
- }
494
- }],
495
-
496
- // 设置分区(契约 §3):keystone 读写/GUI;本处纯逻辑。diagnose/meta 必须同步。
497
- settings: {
498
- keys: ['defaultModel'],
499
- defaults: () => ({ defaultModel: '' }),
500
- normalize(raw) {
501
- const src = raw && typeof raw === 'object' ? raw : {}
502
- return { defaultModel: (typeof src.defaultModel === 'string' && src.defaultModel.trim()) ? src.defaultModel.trim() : '' }
503
- },
504
- meta(envArg) {
505
- const e = envArg && typeof envArg === 'object' ? envArg : env
506
- // 下拉选项:实时 `mimo models`(失败则退化为空 → 面板仍可自由输入)。
507
- let options = []
508
- try {
509
- options = fetchMimoModelsSync(e, 8000).map((m) => ({ value: m.id, label: m.id }))
510
- } catch (err) { options = [] }
511
- return {
512
- titleSuffix: 'MiMo',
513
- fields: [{
514
- key: 'defaultModel', label: '默认模型', type: 'select', allowCustom: true,
515
- options: options,
516
- placeholder: '留空 = 不传 --model(由 mimo CLI 自身默认决定)',
517
- note: options.length
518
- ? '共 ' + options.length + ' 个可用模型(来自 `mimo models`)。mimo_run/mimo_continue 的 model 参数可单次覆盖。'
519
- : '未能读取模型列表(mimo CLI 未安装/未登录/超时)—— 仍可手动输入 provider/model,如 xiaomi/mimo-v2.6-flash。'
520
- }]
521
- }
522
- },
523
- // 同步一行诊断:当前模型 + exe 来源(env > 已知安装位置 > PATH)。
524
- diagnose(settings, envArg) {
525
- const s = settings && typeof settings === 'object' ? settings : {}
526
- const e = envArg && typeof envArg === 'object' ? envArg : env
527
- const model = s.defaultModel ? 'model=' + s.defaultModel : 'model=(未设置 → 不传 --model)'
528
- if (e.MIMO_BIN || e.MIMO_CLI) return model + ' · bin=env:' + (e.MIMO_BIN || e.MIMO_CLI)
529
- const found = mimoCandidateExePaths(e)
530
- return model + ' · ' + (found.length ? 'bin=' + found[0] : 'bin=PATH:mimo')
531
- }
532
- },
533
-
534
- // MCP 形态扩展:**不含 version**。历史:四处 `mcp: { version: '0.2.2' }` 与
535
- // mcp/version.mjs 的 packageVersion() 双源,漏改一处就出现「统一 server 报 0.2.3、
536
- // provider 面仍报 0.2.2」的自相矛盾输出;且 mcp/version.mjs 依赖 import.meta + node:fs,
537
- // 其函数体无法随本文件内联进 dynamic 沙箱(build 文本拼接会丢实现/炸语法)。
538
- // 定案:版本号单一来源 = mcp/version.mjs 的 packageVersion(),由 MCP 面(mcp/providers/
539
- // mimo.mjs 的 meta.version)读取;描述符不复制 version 字面量,宿主如需注入可经 deps.mcp。
540
- mcp: (deps.mcp && typeof deps.mcp === 'object') ? Object.assign({}, deps.mcp) : {}
541
- }
542
-
543
- // 统一分区写入(tmp→rename 原子写;与 keystone lib/settings.mjs 同文件同分区规则,
544
- // 本工具自实现落盘 —— 不 import home-plugin;宿主给出 settingsPath 或 dshHome)。
545
- async function writePartition(fsMod, pathMod, knownPath, home, environment, cur, patch) {
546
- const file = knownPath || environment.CLI_BRIDGE_SETTINGS_FILE || (home ? pathMod.join(home, 'cli-bridge-settings.json') : null)
547
- if (!file) throw new Error('dsh-home not resolved (set DSH_HOME or CLI_BRIDGE_SETTINGS_FILE)')
548
- let all = {}
549
- try { all = JSON.parse(fsMod.readFileSync(file, 'utf8')) } catch (e) { all = {} }
550
- if (!all || typeof all !== 'object') all = {}
551
- const next = Object.assign({}, all)
552
- const part = Object.assign({}, cur, next.mimo || {})
553
- if (patch && patch.defaultModel) part.defaultModel = patch.defaultModel
554
- next.mimo = descriptor.settings.normalize(part)
555
- next.updatedAt = Date.now()
556
- try { fsMod.mkdirSync(pathMod.dirname(file), { recursive: true }) } catch (e) { }
557
- const tmp = file + '.tmp-' + ((typeof process !== 'undefined' && process.pid) || 'mimo')
558
- fsMod.writeFileSync(tmp, JSON.stringify(next, null, 2), 'utf8')
559
- fsMod.renameSync(tmp, file)
560
- return file
561
- }
562
-
563
- // 三形态共用的工具逻辑。签名保持不变(keystone 与队友按此接线)。
564
- // 旧 mimo preset 语义:background 默认 true(仅显式 false 才前台阻塞)。
565
- descriptor.runToolLogic = async function (args, exec) {
566
- const a = args || {}
567
- const normalized = a.background === undefined ? Object.assign({}, a, { background: true }) : a
568
- return this.runner.coreExecute(normalized, exec)
569
- }
570
- descriptor.continueToolLogic = async function (args, exec) {
571
- const a = args || {}
572
- const mapped = { prompt: a.prompt, mode: a.mode, model: a.model, effort: a.effort, cwd: a.cwd, timeoutSec: a.timeoutSec, background: a.background, sessionId: a.sessionId }
573
- if (a.sessionId) mapped.sessionId = a.sessionId
574
- else if (a.latest) mapped.continueLatest = true
575
- return this.runToolLogic(mapped, exec)
576
- }
577
- // 旧 statusTool.execute verbatim:cwd 过滤到单项目(Object.assign 形式与 opencode 一致)。
578
- descriptor.statusToolLogic = async function (args) {
579
- const a = args || {}
580
- const snap = this.engine.statusSnapshot()
581
- if (a.cwd) {
582
- const key = String(a.cwd)
583
- snap.projects = (snap.projects || []).filter((p) => p.cwd === key)
584
- const g = snap.projects[0]
585
- if (g) {
586
- Object.assign(snap, {
587
- state: g.state, running: g.running, current: g.current, trail: g.trail,
588
- lastStatus: g.lastStatus, lastAt: g.lastAt, lastSessionId: g.lastSessionId,
589
- lastOk: g.lastOk, lastFailed: g.lastFailed, fallbackActive: g.fallbackActive,
590
- runs: g.runs, totalTokens: g.totalTokens, updatedAt: g.updatedAt
591
- })
592
- }
593
- }
594
- return snap
595
- }
596
- // 工厂装配(provider 无关骨架 + 描述符);宿主注入 getSettings 时把面板偏好带进 buildArgv。
597
- descriptor.attach = function (hostOpts) {
598
- host = hostOpts || {}
599
- try {
600
- if (typeof host.getSettings === 'function') {
601
- const s = host.getSettings('mimo')
602
- if (s && typeof s === 'object') settingsRef = descriptor.settings.normalize(s)
603
- }
604
- } catch (e) { }
605
- this.engine = createStatusEngine({ provider: this, publish: host.publish })
606
- const runner = createRunner(Object.assign({}, host, { provider: this, engine: this.engine }))
607
- this.runner = runner
608
- return runner
609
- }
610
- // 测试/宿主可见的纯函数面(不进协议字段)。currentSettings/liveSettings/writePartition 是
611
- // 闭包函数,不依赖 attach(未 attach 时 host 为 null → 走 deps 注入或默认空值),测试可
612
- // 直接调用;writePartition 需要调用方自行传入可用的 fs/path 模块。
613
- descriptor._internals = { MIMO_LIMIT_RE, parseMimoJson, buildResult,
614
- mimoCandidateExePaths, resolveMimoExePrefix, parseMimoModels, fetchMimoModelsSync,
615
- currentSettings, liveSettings, writePartition
616
- }
617
- return descriptor
618
- }
1
+ // providers/mimo.mjs — mimo provider descriptor(单后端:本地 mimo CLI / MiMoCode)。
2
+ //
3
+ // 移植基线:mimo-first-bridge v1.x 仓 core/mimo-core.mjs + core/runtime-settings.mjs +
4
+ // preset/mimo-first/mimo-first-bridge.mjs 的内联逻辑(buildArgv / parseMimoJson /
5
+ // buildResult / 三工具 schema / mimo_settings),语义逐字保持;与 provider 无关的骨架
6
+ // (状态引擎/行流/回退弹窗/展示层/超时护栏)在 core/bridge-kit.mjs(契约 §1)。
7
+ //
8
+ // 2026-10 去 desktop 化(用户定案:MiMo 免费 API 服务已被官方终止 + 本机 0 凭据):
9
+ // 1. 取消 mimo-desktop 后端 —— 只走 `mimo run`(MiMoCode CLI,官方便携安装位置
10
+ // ~/.mimocode/bin/mimo.exe);登录由用户在 CLI 侧 `mimo auth login` 自理。
11
+ // 2. 模型由用户在设置里手动指定(settings.defaultModel,不写死默认值);留空 =
12
+ // 不传 --model,交给 mimo CLI 自身默认。可用模型以 `mimo models` 实测为准
13
+ // (xiaomi/mimo-v2.6-flash / -pro / -pro-ultraspeed 等)。
14
+ // 3. 是否启用 mimo 由调度(_scheduling.enabled)控制;本描述符不含任何开关。
15
+ //
16
+ // 红线(PROVIDER-CONTRACT.md §8 + Lead 定案):本文件会被 build 内联进 dynamic 沙箱
17
+ // (new Function)—— 绝不出现 import.meta 字面量;process/fs/child_process 只经
18
+ // globalThis.process.getBuiltinModule + typeof 守卫读取;只允许 import bridge-kit。
19
+ import { createStatusEngine, createRunner, clampInt, shortLabel, summarizeArgs } from '../core/bridge-kit.mjs'
20
+ import { parseMimoJson, buildResult } from './mimo-pure.mjs'
21
+
22
+ // ── 单后端归一(旧 mimo-core 双后端 verbatim 的收缩形态)───────────────────────
23
+ // mimo-desktop 取消后不再有第二后端:backends() 恒 null;任何输入(含历史别名
24
+ // mimocode / mimo-cli / desktop / 空串 / 非法值)一律归一为 null。会话路由由
25
+ // engine.resolveTarget(cwd + sessionId)完成,backend 恒 null。
26
+ const DEFAULT_TIMEOUT_SEC = 600
27
+
28
+ // 旧 LIMIT_RE(比 kit 版多 free-API/登录/第三方等 MiMo 文案;provider.isLimited 覆盖)。
29
+ // 命名 MIMO_ 前缀:dynamic 内联时 kit 也声明顶层 LIMIT_RE,同名会在同一脚本作用域
30
+ // 触发「Identifier already declared」构建错误(scripts/build.mjs 文本拼接的固有约束)。
31
+ const MIMO_LIMIT_RE = /rate.?limit|ratelimit|429|too many|quota|insufficient|credit|balance|exhausted|exceed|network|offline|ENETUNREACH|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|timeout|timed out|unavailable|503|502|500|401|403|unauthorized|invalid api|api key|connection|proxy|socket|tls|ssl|dns|free API service has ended|sign in|configure a third-party|网络|超时|限流|流量|受限|配额|金额|余额|额度|认证|连接|断开|登录|第三方/i
32
+
33
+ // ── Node 内建探测(沙箱纪律:getBuiltinModule + typeof 守卫)───────────────────
34
+ // 名字带 mimo 前缀:本文件会与 bridge-kit / core/scheduling.mjs【文本内联进同一个动态
35
+ // 沙箱脚本作用域】,撞名即「Identifier already declared」构建错误。
36
+ function mimoBuiltin(name) {
37
+ try {
38
+ const proc = globalThis.process
39
+ return (proc && typeof proc.getBuiltinModule === 'function') ? proc.getBuiltinModule(name) : null
40
+ } catch (e) { return null }
41
+ }
42
+
43
+ // ── 可执行文件解析(env MIMO_BIN/MIMO_CLI > 已知安装位置 > PATH 名字)───────────
44
+ // MiMoCode CLI 官方便携安装目录:<USERPROFILE|HOME>/.mimocode/bin/mimo[.exe]。
45
+ // 沙箱内可能没有 fs —— 全部读取走 typeof 守卫,读不到就返回空数组(退回 PATH 查找)。
46
+ const MIMO_EXE_DIR = ['.mimocode', 'bin']
47
+
48
+ /** 探测本机 mimo 可执行文件候选路径(官方便携安装位置);无 fs 能力时返回空数组。 */
49
+ export function mimoCandidateExePaths(env) {
50
+ const e = env || {}
51
+ const out = []
52
+ const fs = mimoBuiltin('node:fs')
53
+ if (!fs || typeof fs.existsSync !== 'function') return out
54
+ const path = mimoBuiltin('node:path')
55
+ const join = (path && typeof path.join === 'function') ? ((a, b) => path.join(a, b)) : ((a, b) => a + '/' + b)
56
+ for (const k of ['USERPROFILE', 'HOME']) {
57
+ if (!e[k]) continue
58
+ const dir = join(join(String(e[k]), MIMO_EXE_DIR[0]), MIMO_EXE_DIR[1])
59
+ for (const base of ['mimo.exe', 'mimo']) {
60
+ const exe = join(dir, base)
61
+ try { if (fs.existsSync(exe) && out.indexOf(exe) < 0) out.push(exe) } catch (err) { /* 探测失败静默跳过 */ }
62
+ }
63
+ }
64
+ return out
65
+ }
66
+
67
+ /**
68
+ * 解析本次调用使用的 exe 前缀(数组或字符串)。
69
+ * 优先级:binPath(显式路径)> env MIMO_BIN/MIMO_CLI > 已知安装位置 > PATH 名字。
70
+ */
71
+ export function resolveMimoExePrefix(env, binPath) {
72
+ const e = env || {}
73
+ const bin = binPath || e.MIMO_BIN || e.MIMO_CLI || ''
74
+ if (bin) {
75
+ if (/\.(mjs|cjs|js)$/i.test(bin)) {
76
+ const proc = globalThis.process
77
+ return [(proc && proc.execPath) ? proc.execPath : 'node', bin]
78
+ }
79
+ return [String(bin)]
80
+ }
81
+ const found = mimoCandidateExePaths(e)
82
+ return found.length ? [found[0]] : ['mimo']
83
+ }
84
+
85
+ // ── 模型列表(`mimo models`;设置面板下拉用)───────────────────────────────────
86
+ // 实测输出形如每行 `provider/model — window 1M, compacts at 900K`(分隔符是中文破折号
87
+ // U+2014)。模型名自身含连字符(xiaomi/mimo-v2.6-pro-ultraspeed),所以只认「行首的
88
+ // provider/model」,其后一律当描述文本;表头/说明/空行一律丢弃,绝不抛。
89
+ const MIMO_MODEL_ID_RE = /^([A-Za-z0-9_.-]+\/[A-Za-z0-9_.@#+-]+)(?=$|[\s—–:|,])/
90
+
91
+ /** 解析 `mimo models` 文本输出为 [{id, provider, name, note}](去重、保序)。 */
92
+ export function parseMimoModels(text) {
93
+ const out = []
94
+ const seen = Object.create(null)
95
+ for (const raw of String(text || '').split(/\r?\n/)) {
96
+ // 去掉列表记号(• * - 1. 等)与行首空白,避免把记号当 provider 名。
97
+ const ln = raw.replace(/^[^A-Za-z0-9]+/, '').trim()
98
+ if (!ln) continue
99
+ const m = ln.match(MIMO_MODEL_ID_RE)
100
+ if (!m) continue
101
+ const id = m[1]
102
+ if (seen[id]) continue
103
+ seen[id] = true
104
+ const slash = id.indexOf('/')
105
+ out.push({ id: id, provider: id.slice(0, slash), name: id.slice(slash + 1), note: ln.slice(id.length).replace(/^[\s—–:|,-]+/, '').trim() })
106
+ }
107
+ return out
108
+ }
109
+
110
+ /**
111
+ * 同步抓取模型列表(供设置面板下拉)。失败返回空数组 —— 下拉退化为自由输入,
112
+ * 绝不因探测失败影响面板渲染。仅 spawnSync 可用时生效(宿主形态)。
113
+ */
114
+ export function fetchMimoModelsSync(env, timeoutMs) {
115
+ try {
116
+ const child = mimoBuiltin('node:child_process')
117
+ if (!child || typeof child.spawnSync !== 'function') return []
118
+ const prefix = resolveMimoExePrefix(env)
119
+ const r = child.spawnSync(prefix[0], prefix.slice(1).concat(['models']), { encoding: 'utf8', timeout: clampInt(timeoutMs, 8000, 1000, 30000), windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
120
+ if (!r || r.error || r.status !== 0) return []
121
+ return parseMimoModels(String(r.stdout || ''))
122
+ } catch (e) { return [] }
123
+ }
124
+
125
+ // ── 三工具 schema(旧 preset verbatim;desktop 专属入参已随之后端取消而删除)────
126
+ const MODEL_DESC = 'provider/model 格式,如 xiaomi/mimo-v2.6-flash;留空用设置里的默认模型'
127
+ const RUN_PARAMS = {
128
+ type: 'object', additionalProperties: true, required: ['prompt'],
129
+ properties: {
130
+ prompt: { type: 'string', description: 'The task instruction for mimo. On first dispatch for a topic, include a compact CONTEXT preamble (goal, repo root, key paths, decisions/constraints; point at paths, do not paste file contents — mimo reads the repo itself). For follow-ups on the same topic, use mimo_continue with latest=true or sessionId (mimo keeps conversation context; state only what is new).' },
131
+ mode: { type: 'string', enum: ['auto', 'plan', 'build', 'compose', 'accept-edits'], description: 'auto follows DSH plan state (plan vs build); plan = read-only analysis (--agent plan); build = full tools (--agent build); compose = compose workflow.' },
132
+ model: { type: 'string', description: MODEL_DESC },
133
+ effort: { type: 'string', enum: ['low', 'medium', 'high'], description: 'Optional reasoning effort, mapped to mimo --variant (low→minimal, high→high).' },
134
+ cwd: { type: 'string', description: 'Working directory for mimo (--dir).' },
135
+ timeoutSec: { type: 'integer', description: 'Hard timeout seconds (10-3600, default 600). Grace +60s on top.' },
136
+ background: { type: 'boolean', description: 'Defaults to true: dispatch returns a jobId immediately; collect with job_output, watch progress with mimo_status. Set false to block for the final answer.' },
137
+ sessionId: { type: 'string', description: 'Optional mimo session id to resume (--session). Follow-ups on the same topic normally go through mimo_continue.' },
138
+ title: { type: 'string', description: 'Optional session title.' }
139
+ }
140
+ }
141
+ const CONTINUE_PARAMS = {
142
+ type: 'object', additionalProperties: true, required: ['prompt'],
143
+ properties: {
144
+ prompt: { type: 'string', description: 'Follow-up instruction for the ongoing mimo session. State only what is new; mimo preserves its conversation context.' },
145
+ sessionId: { type: 'string', description: 'mimo session id to resume (--session).' },
146
+ latest: { type: 'boolean', description: 'Continue the most recent mimo session (--continue).' },
147
+ mode: { type: 'string', enum: ['auto', 'plan', 'build', 'compose', 'accept-edits'], description: 'Execution mode.' },
148
+ model: { type: 'string', description: MODEL_DESC },
149
+ effort: { type: 'string', enum: ['low', 'medium', 'high'], description: 'Optional reasoning effort.' },
150
+ cwd: { type: 'string', description: 'Working directory for mimo.' },
151
+ timeoutSec: { type: 'integer', description: 'Hard timeout seconds (10-3600, default 600).' },
152
+ background: { type: 'boolean', description: 'Defaults to true (background job).' }
153
+ }
154
+ }
155
+ const STATUS_PARAMS = { type: 'object', additionalProperties: true, required: [], properties: { cwd: { type: 'string', description: 'Optional: filter the snapshot to a single project (working directory).' } } }
156
+ const SETTINGS_PARAMS = { type: 'object', additionalProperties: true, required: [], properties: { model: { type: 'string', description: MODEL_DESC } } }
157
+ const SETTINGS_DESCRIPTION = 'Read or change the default mimo model (settings). Call with model=<provider/model> to save it as the default for subsequent mimo_run/mimo_continue; call with no args to read current settings. Persisted to the settings file; a per-call `model` argument on mimo_run/mimo_continue overrides it for that call only. Available models are listed by `mimo models` on this machine (mimo CLI must be installed and logged in).'
158
+
159
+ function renderSettings(value) {
160
+ const s = value || {}
161
+ const lines = [
162
+ 'mimo settings',
163
+ ' settings file : ' + (s.settingsPath || '(unknown)'),
164
+ ' default model : ' + (s.defaultModel || '(unset — 不传 --model)'),
165
+ ' effective : ' + (s.effective || '(unknown)'),
166
+ ' exe : ' + (s.exe || '(unknown)'),
167
+ ' saved : ' + (s.saved ? 'yes' : 'no')
168
+ ]
169
+ if (s.saveError) lines.push(' save error : ' + s.saveError)
170
+ if (s.note) lines.push(' note : ' + s.note)
171
+ return [{ type: 'text', text: lines.join('\n') }]
172
+ }
173
+ // ── 可纯函数化的 mimo-core 语义(descriptor 方法 + 独立导出双份)───────────────
174
+
175
+ export default function defineProvider(deps = {}) {
176
+ const env = deps.env || {}
177
+ const nodeFs = deps.nodeFs || null
178
+ const nodePath = deps.nodePath || null
179
+ let host = null // attach 后保存 hostOpts(preset/dynamic 形态提供 getSettings)
180
+ let settingsRef = { defaultModel: '' }
181
+
182
+ /** 取当前生效的偏好设置。三条来源按优先级合并,每次 buildArgv 都重新读 ——
183
+ * 面板改默认模型后无需重启即生效:
184
+ * 1) `host.getSettings('mimo')` —— preset/dynamic 形态(attach 时由宿主注入);
185
+ * 2) `deps.readSettings()` —— MCP 形态(真 Node 进程,每次现读设置文件);
186
+ * 3) `settingsRef` —— attach 时固化的一次性快照 / 缺省值。
187
+ * 三条都拿不到 → 缺省 `{defaultModel:''}`(= 不传 --model,交给 mimo CLI 自决)。
188
+ *
189
+ * 历史坑:MCP 形态不 attach(自建 engine),只认 host.getSettings 会让面板设置的
190
+ * defaultModel 在 MCP 面对 mimo_run 完全失效 —— 只有 args.model 才落地。
191
+ * 三个形态行为不一致是缺陷,故此处统一把 readSettings 纳入。 */
192
+ function currentSettings() {
193
+ const out = Object.assign({}, settingsRef)
194
+ try {
195
+ if (typeof deps.readSettings === 'function') {
196
+ const r = deps.readSettings()
197
+ if (r && typeof r === 'object') {
198
+ // 宿主可返回 { partition, path, home } 或直接返回分区对象(宽松兼容)。
199
+ const part = ('partition' in r || 'path' in r || 'home' in r) ? r.partition : r
200
+ if (part && typeof part === 'object') Object.assign(out, part)
201
+ }
202
+ }
203
+ } catch (e) { }
204
+ try {
205
+ if (host && typeof host.getSettings === 'function') {
206
+ const s = host.getSettings('mimo')
207
+ if (s && typeof s === 'object') Object.assign(out, s)
208
+ }
209
+ } catch (e) { }
210
+ return out
211
+ }
212
+
213
+ // 模型优先级:调用参数 > 宿主注入设置 > runner opts 透传 > 空(不传 --model)。
214
+ // 用户要求「不设默认 → 由 mimo CLI 自决」,故空值绝不落地 --model。
215
+ function effectiveModel(args, opts) {
216
+ const o = opts || {}
217
+ const fromArg = (args && args.model && String(args.model).trim()) || ''
218
+ if (fromArg) return fromArg
219
+ const fromSettings = (currentSettings().defaultModel || '').trim()
220
+ if (fromSettings) return fromSettings
221
+ const fromOpts = (o.settings && o.settings.defaultModel) || o.defaultModel
222
+ return fromOpts ? String(fromOpts).trim() : ''
223
+ }
224
+
225
+ // ── 统一设置分区读取(keystone 落盘;descriptor 只读)。宿主注入 deps.readSettings
226
+ // 动态读取(preset/MCP 每次取最新文件值),或静态 deps.settings(测试/dynamic)。
227
+ function liveSettings() {
228
+ if (typeof deps.readSettings === 'function') {
229
+ try {
230
+ const r = deps.readSettings()
231
+ if (r && typeof r === 'object') {
232
+ // 宿主可返回 { partition, path, home } 或直接返回分区对象(宽松兼容)。
233
+ if ('partition' in r || 'path' in r || 'home' in r) {
234
+ return { partition: r.partition || null, path: r.path || null, home: r.home || null }
235
+ }
236
+ return { partition: r, path: deps.settingsPath || null, home: deps.dshHome || null }
237
+ }
238
+ } catch (e) { }
239
+ }
240
+ return { partition: (deps.settings && typeof deps.settings === 'object') ? deps.settings : null, path: deps.settingsPath || null, home: deps.dshHome || null }
241
+ }
242
+
243
+ const descriptor = {
244
+ id: 'mimo', label: 'MIMO', presetId: 'cordis-mimo', defaultBackend: null, defaultMode: 'auto',
245
+ exeName: 'mimo', binEnvVars: ['MIMO_BIN', 'MIMO_CLI'], unavailableStatus: 'MIMO_UNAVAILABLE',
246
+
247
+ // 单后端:backends() 恒 null;历史别名(mimocode/mimo-cli/desktop)与非法值一律
248
+ // 归一为 null(契约 §1:非法输入返回 null)。
249
+ backends() { return null },
250
+ normalizeBackend() { return null },
251
+ resolveBackend(args, target, preferred) { return null },
252
+
253
+ // 旧 preset buildArgv(exe, args, planActive) verbatim 语义(execPrefix 可为
254
+ // [nodeExe, binPath] 数组,runner 已归一)。
255
+ buildArgv(exePrefix, args, opts) {
256
+ const o = opts || {}
257
+ const timeoutSec = clampInt(args.timeoutSec, DEFAULT_TIMEOUT_SEC, 10, 3600)
258
+ const argv = Array.isArray(exePrefix) ? exePrefix.slice() : [String(exePrefix)]
259
+ argv.push('run')
260
+ if (args.prompt != null && String(args.prompt).length) argv.push(String(args.prompt))
261
+ argv.push('--format', 'json', '--dangerously-skip-permissions')
262
+ let mode = args.mode || o.defaultMode || 'auto'
263
+ if (mode === 'auto') mode = o.planActive ? 'plan' : 'build'
264
+ if (mode === 'accept-edits') mode = 'build'
265
+ // mimo --agent: build | plan | compose
266
+ const agent = args.agent || mode
267
+ if (agent === 'plan' || agent === 'build' || agent === 'compose') argv.push('--agent', agent)
268
+ // 模型:调用参数 > 设置 defaultModel > 不传(mimo CLI 自身默认)。
269
+ const model = effectiveModel(args, o)
270
+ if (model) argv.push('--model', String(model))
271
+ // effort (low/medium/high) maps to mimo --variant; pass-through if already a variant name
272
+ let variant = args.variant || args.effort
273
+ if (variant === 'low') variant = 'minimal'
274
+ else if (variant === 'medium') variant = undefined
275
+ else if (variant === 'high') variant = 'high'
276
+ if (variant) argv.push('--variant', String(variant))
277
+ if (args.cwd) argv.push('--dir', String(args.cwd))
278
+ if (args.sessionId) argv.push('--session', String(args.sessionId))
279
+ else if (args.continueLatest) argv.push('--continue')
280
+ if (args.title) argv.push('--title', String(args.title))
281
+ return { argv, timeoutSec, mode: agent }
282
+ },
283
+
284
+ parseJson: parseMimoJson,
285
+ buildResult,
286
+
287
+ // 旧 foldStepUpdate 语义 verbatim(识别 tool/text/error 事件),trail 条目同时带
288
+ // kit 展示层字段(stepIndex/tool/state/args)与旧字段(kind/label),这样
289
+ // renderStatus 与 MCP 快照映射(buildMcpBridgePayload)都能直接渲染。
290
+ foldStreamEvent(ev, p, summarizeArgsFn, maxArgLen, maxTrail) {
291
+ if (!ev || typeof ev !== 'object') return
292
+ const t = ev.type
293
+ const pr = ev.properties || ev
294
+ const cap = maxTrail || 12
295
+ const idx = p.trail ? p.trail.length : 0
296
+ let entry = null
297
+ if (t === 'tool' || t === 'tool-call' || t === 'tool_use' || t === 'step_update') {
298
+ const name = pr.tool_name || pr.tool || pr.name
299
+ if (name) {
300
+ const args = (summarizeArgsFn || summarizeArgs)(pr.arguments || pr.args || pr.input) || null
301
+ const state = pr.state || pr.status || 'ACTIVE'
302
+ entry = {
303
+ at: Date.now(), kind: 'tool', stepIndex: idx, tool: String(name), args, state,
304
+ label: shortLabel(name + ' ' + JSON.stringify(args || {}))
305
+ }
306
+ if (state === 'ACTIVE') p.current = { tool: String(name), args, stepIndex: idx, since: entry.at }
307
+ else if (p.current && p.current.tool === String(name) && p.current.stepIndex === idx) p.current = null
308
+ }
309
+ } else if (t === 'text' || t === 'message') {
310
+ const chunk = pr.text || pr.content || ''
311
+ if (typeof chunk === 'string' && chunk) {
312
+ const capLen = maxArgLen || 120
313
+ entry = { at: Date.now(), kind: 'text', stepIndex: idx, tool: 'agent_response', args: { text: chunk.slice(0, capLen) }, state: 'ACTIVE', label: shortLabel(chunk) }
314
+ p.current = { tool: 'agent_response', args: entry.args, stepIndex: idx, since: entry.at }
315
+ }
316
+ } else if (t === 'error') {
317
+ const err = pr.error || pr
318
+ const msg = (err.data && err.data.message) || err.message || 'error'
319
+ entry = { at: Date.now(), kind: 'error', stepIndex: idx, tool: 'error', args: { message: String(msg).slice(0, maxArgLen || 120) }, state: 'FAILED', label: shortLabel(msg) }
320
+ }
321
+ if (entry && p.trail) {
322
+ p.trail.push(entry)
323
+ while (p.trail.length > cap) p.trail.shift()
324
+ }
325
+ },
326
+
327
+ // 旧 LIMIT_RE 覆盖(kit 版不含 free API/登录/第三方等 MiMo 文案)。
328
+ isLimited(res) {
329
+ if (!res || res.ok) return false
330
+ if (res.status === 'SPAWN_ERROR' || res.status === 'MIMO_UNAVAILABLE' || res.status === 'HUNG_TIMEOUT') return true
331
+ const hay = String(res.stderr || '') + ' ' + String(res.response || '') + ' ' + String(res.status || '') + ' ' + String(res.errorMessage || '')
332
+ return MIMO_LIMIT_RE.test(hay)
333
+ },
334
+
335
+ failureHint(res) {
336
+ if (!res || res.ok) return ''
337
+ const st = String(res.status || '')
338
+ if (st === 'MIMO_UNAVAILABLE') return '[诊断] 未找到 mimo 可执行文件:请安装 MiMoCode CLI(mimo,官方便携安装位置 ~/.mimocode/bin/mimo.exe),或设置 MIMO_BIN 指向其绝对路径。'
339
+ const hay = String(res.stderr || '') + ' ' + String(res.errorMessage || '') + ' ' + String(res.response || '')
340
+ if (/free API service has ended|sign in|configure a third-party|登录|第三方|免费/i.test(hay)) {
341
+ return '[诊断] MiMo 免费 API 已终止,请在 mimo CLI 用 `mimo auth login` 登录或配置第三方 API,并在 CLI Bridge 设置里指定模型。'
342
+ }
343
+ if (/model not found|unknown model|no models available|invalid model|unknown provider/i.test(hay)) {
344
+ return '[诊断] mimo 模型不可用或模型名无效:先在本机运行 `mimo models` 列出可用模型,再把 provider/model 填进 CLI Bridge 的「默认模型」设置(或本次调用的 model 参数)。'
345
+ }
346
+ return ''
347
+ },
348
+
349
+ // ACCEPTED 计入成功态(指示灯不红;契约 §1);desktop 取消后不再产生 ACCEPTED,
350
+ // 但成功态集合逐字保持不变(兼容旧会话/测试语义)。
351
+ isSuccessStatus(st) {
352
+ if (!st) return false
353
+ return st === 'SUCCESS' || st === 'ACCEPTED'
354
+ },
355
+
356
+ tools: {
357
+ run: { name: 'mimo_run', description: 'Dispatch a coding/build/debug/investigation task to the local mimo agent CLI (Xiaomi MiMoCode) and return its final answer. DSH fully controls mimo (--dangerously-skip-permissions; mimo never prompts). On rate-limit/network failure DSH pops a fallback dialog; fallback=true means finish with native tools. Runs in the background by default (returns a jobId immediately; collect with job_output); set background=false to block for the final answer. While it runs, call mimo_status to watch what mimo is doing live.', inputSchema: RUN_PARAMS },
358
+ continue: { name: 'mimo_continue', description: 'Continue an existing mimo session with a follow-up prompt. Pass sessionId or set latest=true. Same DSH-controlled, no-prompt execution and same fallback dialog as mimo_run.', inputSchema: CONTINUE_PARAMS },
359
+ status: { name: 'mimo_status', description: 'Read a live snapshot of what the local mimo agent is currently doing. Returns one section per project (working directory): running count, current step, recent step trail, last completed run status + session id, per-project runs/token usage. Call this to check on an in-flight mimo_run/mimo_continue without waiting for it to finish.', inputSchema: STATUS_PARAMS }
360
+ },
361
+
362
+ // mimo_settings:入参键保持旧 prompt 连续性(backend/desktopModel → model),落统一
363
+ // 分区 defaultModel(迁移映射 keystone 已做)。写盘仅在宿主注入 nodeFs + nodePath 时
364
+ // 可用;否则回显(dynamic 沙箱旧 echo 语义)。
365
+ extraTools: [{
366
+ name: 'mimo_settings',
367
+ description: SETTINGS_DESCRIPTION,
368
+ inputSchema: SETTINGS_PARAMS,
369
+ render: renderSettings,
370
+ async logic(args) {
371
+ const a = args || {}
372
+ const live = liveSettings()
373
+ const cur = Object.assign({ defaultModel: '' }, live.partition || {})
374
+ let settingsPath = live.path || null
375
+ let saved = false, saveError = null
376
+ const home = live.home || deps.dshHome || null
377
+ const patch = (typeof a.model === 'string' && a.model.trim()) ? { defaultModel: a.model.trim() } : null
378
+ if (patch && nodeFs && nodePath && (settingsPath || home)) {
379
+ try { settingsPath = await writePartition(nodeFs, nodePath, settingsPath, home, env, cur, patch); saved = true } catch (e) { saveError = String(e && e.message || e) }
380
+ }
381
+ const merged = Object.assign({}, cur)
382
+ if (patch) merged.defaultModel = patch.defaultModel
383
+ return {
384
+ ok: !saveError,
385
+ settingsPath: settingsPath || '(unified; not writable in this host)',
386
+ defaultModel: merged.defaultModel || '',
387
+ effective: merged.defaultModel ? ('settings:' + merged.defaultModel) : '(unset — 不传 --model,mimo CLI 自决)',
388
+ exe: resolveMimoExePrefix(env).join(' '),
389
+ saved, saveError,
390
+ note: '默认模型在设置面板或本工具里指定(provider/model);mimo_run/mimo_continue 的 model 参数可单次覆盖。可用模型:在本机运行 `mimo models` 查看。'
391
+ }
392
+ }
393
+ }],
394
+
395
+ // 设置分区(契约 §3):keystone 读写/GUI;本处纯逻辑。diagnose/meta 必须同步。
396
+ settings: {
397
+ keys: ['defaultModel'],
398
+ defaults: () => ({ defaultModel: '' }),
399
+ normalize(raw) {
400
+ const src = raw && typeof raw === 'object' ? raw : {}
401
+ return { defaultModel: (typeof src.defaultModel === 'string' && src.defaultModel.trim()) ? src.defaultModel.trim() : '' }
402
+ },
403
+ meta(envArg) {
404
+ const e = envArg && typeof envArg === 'object' ? envArg : env
405
+ // 下拉选项:实时 `mimo models`(失败则退化为空 → 面板仍可自由输入)。
406
+ let options = []
407
+ try {
408
+ options = fetchMimoModelsSync(e, 8000).map((m) => ({ value: m.id, label: m.id }))
409
+ } catch (err) { options = [] }
410
+ return {
411
+ titleSuffix: 'MiMo',
412
+ fields: [{
413
+ key: 'defaultModel', label: '默认模型', type: 'select', allowCustom: true,
414
+ options: options,
415
+ placeholder: '留空 = 不传 --model(由 mimo CLI 自身默认决定)',
416
+ note: options.length
417
+ ? '共 ' + options.length + ' 个可用模型(来自 `mimo models`)。mimo_run/mimo_continue 的 model 参数可单次覆盖。'
418
+ : '未能读取模型列表(mimo CLI 未安装/未登录/超时)—— 仍可手动输入 provider/model,如 xiaomi/mimo-v2.6-flash。'
419
+ }]
420
+ }
421
+ },
422
+ // 同步一行诊断:当前模型 + exe 来源(env > 已知安装位置 > PATH)。
423
+ diagnose(settings, envArg) {
424
+ const s = settings && typeof settings === 'object' ? settings : {}
425
+ const e = envArg && typeof envArg === 'object' ? envArg : env
426
+ const model = s.defaultModel ? 'model=' + s.defaultModel : 'model=(未设置 → 不传 --model)'
427
+ if (e.MIMO_BIN || e.MIMO_CLI) return model + ' · bin=env:' + (e.MIMO_BIN || e.MIMO_CLI)
428
+ const found = mimoCandidateExePaths(e)
429
+ return model + ' · ' + (found.length ? 'bin=' + found[0] : 'bin=PATH:mimo')
430
+ }
431
+ },
432
+
433
+ // MCP 形态扩展:**不含 version**。历史:四处 `mcp: { version: '0.2.2' }` 与
434
+ // mcp/version.mjs 的 packageVersion() 双源,漏改一处就出现「统一 server 报 0.2.3、
435
+ // provider 面仍报 0.2.2」的自相矛盾输出;且 mcp/version.mjs 依赖 import.meta + node:fs,
436
+ // 其函数体无法随本文件内联进 dynamic 沙箱(build 文本拼接会丢实现/炸语法)。
437
+ // 定案:版本号单一来源 = mcp/version.mjs 的 packageVersion(),由 MCP 面(mcp/providers/
438
+ // mimo.mjs 的 meta.version)读取;描述符不复制 version 字面量,宿主如需注入可经 deps.mcp。
439
+ mcp: (deps.mcp && typeof deps.mcp === 'object') ? Object.assign({}, deps.mcp) : {}
440
+ }
441
+
442
+ // 统一分区写入(tmp→rename 原子写;与 keystone lib/settings.mjs 同文件同分区规则,
443
+ // 本工具自实现落盘 —— 不 import home-plugin;宿主给出 settingsPath 或 dshHome)。
444
+ async function writePartition(fsMod, pathMod, knownPath, home, environment, cur, patch) {
445
+ const file = knownPath || environment.CLI_BRIDGE_SETTINGS_FILE || (home ? pathMod.join(home, 'cli-bridge-settings.json') : null)
446
+ if (!file) throw new Error('dsh-home not resolved (set DSH_HOME or CLI_BRIDGE_SETTINGS_FILE)')
447
+ let all = {}
448
+ try { all = JSON.parse(fsMod.readFileSync(file, 'utf8')) } catch (e) { all = {} }
449
+ if (!all || typeof all !== 'object') all = {}
450
+ const next = Object.assign({}, all)
451
+ const part = Object.assign({}, cur, next.mimo || {})
452
+ if (patch && patch.defaultModel) part.defaultModel = patch.defaultModel
453
+ next.mimo = descriptor.settings.normalize(part)
454
+ next.updatedAt = Date.now()
455
+ try { fsMod.mkdirSync(pathMod.dirname(file), { recursive: true }) } catch (e) { }
456
+ const tmp = file + '.tmp-' + ((typeof process !== 'undefined' && process.pid) || 'mimo')
457
+ fsMod.writeFileSync(tmp, JSON.stringify(next, null, 2), 'utf8')
458
+ fsMod.renameSync(tmp, file)
459
+ return file
460
+ }
461
+
462
+ // 三形态共用的工具逻辑。签名保持不变(keystone 与队友按此接线)。
463
+ // 旧 mimo preset 语义:background 默认 true(仅显式 false 才前台阻塞)。
464
+ descriptor.runToolLogic = async function (args, exec) {
465
+ const a = args || {}
466
+ const normalized = a.background === undefined ? Object.assign({}, a, { background: true }) : a
467
+ return this.runner.coreExecute(normalized, exec)
468
+ }
469
+ descriptor.continueToolLogic = async function (args, exec) {
470
+ const a = args || {}
471
+ const mapped = { prompt: a.prompt, mode: a.mode, model: a.model, effort: a.effort, cwd: a.cwd, timeoutSec: a.timeoutSec, background: a.background, sessionId: a.sessionId }
472
+ if (a.sessionId) mapped.sessionId = a.sessionId
473
+ else if (a.latest) mapped.continueLatest = true
474
+ return this.runToolLogic(mapped, exec)
475
+ }
476
+ // 旧 statusTool.execute verbatim:cwd 过滤到单项目(Object.assign 形式与 opencode 一致)。
477
+ descriptor.statusToolLogic = async function (args) {
478
+ const a = args || {}
479
+ const snap = this.engine.statusSnapshot()
480
+ if (a.cwd) {
481
+ const key = String(a.cwd)
482
+ snap.projects = (snap.projects || []).filter((p) => p.cwd === key)
483
+ const g = snap.projects[0]
484
+ if (g) {
485
+ Object.assign(snap, {
486
+ state: g.state, running: g.running, current: g.current, trail: g.trail,
487
+ lastStatus: g.lastStatus, lastAt: g.lastAt, lastSessionId: g.lastSessionId,
488
+ lastOk: g.lastOk, lastFailed: g.lastFailed, fallbackActive: g.fallbackActive,
489
+ runs: g.runs, totalTokens: g.totalTokens, updatedAt: g.updatedAt
490
+ })
491
+ }
492
+ }
493
+ return snap
494
+ }
495
+ // 工厂装配(provider 无关骨架 + 描述符);宿主注入 getSettings 时把面板偏好带进 buildArgv。
496
+ descriptor.attach = function (hostOpts) {
497
+ host = hostOpts || {}
498
+ try {
499
+ if (typeof host.getSettings === 'function') {
500
+ const s = host.getSettings('mimo')
501
+ if (s && typeof s === 'object') settingsRef = descriptor.settings.normalize(s)
502
+ }
503
+ } catch (e) { }
504
+ this.engine = createStatusEngine({ provider: this, publish: host.publish })
505
+ const runner = createRunner(Object.assign({}, host, { provider: this, engine: this.engine }))
506
+ this.runner = runner
507
+ return runner
508
+ }
509
+ // 测试/宿主可见的纯函数面(不进协议字段)。currentSettings/liveSettings/writePartition 是
510
+ // 闭包函数,不依赖 attach(未 attach 时 host 为 null → 走 deps 注入或默认空值),测试可
511
+ // 直接调用;writePartition 需要调用方自行传入可用的 fs/path 模块。
512
+ descriptor._internals = { MIMO_LIMIT_RE, parseMimoJson, buildResult,
513
+ mimoCandidateExePaths, resolveMimoExePrefix, parseMimoModels, fetchMimoModelsSync,
514
+ currentSettings, liveSettings, writePartition
515
+ }
516
+ return descriptor
517
+ }