@miphamai/cli 0.85.34 → 0.85.36

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.
@@ -22,10 +22,29 @@ import type {
22
22
  ClientInterruptMessage,
23
23
  ClientSetModeMessage,
24
24
  ServerMessage,
25
+ ServerStatsMessage,
25
26
  } from './attach-protocol'
26
27
  import { ALL_MODES } from '../core/permission-config'
27
28
  import type { PermissionMode, StreamChunk } from '../shared/types'
28
29
 
30
+ /**
31
+ * Flatten a message's content (string, or the provider block array) into the
32
+ * plain text local commands display. Unknown shapes become '' rather than
33
+ * `[object Object]`.
34
+ */
35
+ function contentToText(value: unknown): string {
36
+ if (typeof value === 'string') return value
37
+ if (!Array.isArray(value)) return ''
38
+ return value
39
+ .map((block) =>
40
+ typeof block === 'object' && block !== null && typeof (block as any).text === 'string'
41
+ ? ((block as any).text as string)
42
+ : '',
43
+ )
44
+ .filter((text) => text !== '')
45
+ .join(' ')
46
+ }
47
+
29
48
  // ── Public API ───────────────────────────────────────────────────────────────
30
49
 
31
50
  export interface RemoteEngineOptions {
@@ -89,6 +108,25 @@ export class RemoteEngine {
89
108
  /** Viewers of the confirmed mode (the TUI footer). See `onPermissionModeChange`. */
90
109
  private readonly modeListeners = new Set<(mode: PermissionMode) => void>()
91
110
 
111
+ // ── Session readings (the numbers live on the daemon) ────────────────────
112
+ //
113
+ // `getContext()` below is the local stand-in slash commands read. Its numbers
114
+ // come from the daemon's `stats` frames — attach sends one immediately, and
115
+ // one follows every completed turn. Fields are merged individually: the two
116
+ // sides version independently, so a missing or malformed field must leave the
117
+ // previous value (or zero) in place rather than poison the display with NaN.
118
+ private stats: {
119
+ estimatedTokens: number
120
+ maxTokens: number
121
+ compactionThreshold: number
122
+ messageCount: number
123
+ checkpointCount: number
124
+ cachedTokens: number
125
+ } | null = null
126
+
127
+ /** Messages from the last `session_state` snapshot, parsed for local commands. */
128
+ private snapshotMessages: Array<{ role: string; content: string }> = []
129
+
92
130
  /**
93
131
  * One stable object — **not** a fresh closure per `getPermission()` call.
94
132
  *
@@ -322,12 +360,27 @@ export class RemoteEngine {
322
360
  /** No-op: agents run on the daemon. */
323
361
  setAgentRegistry(_reg: unknown): void {}
324
362
 
325
- /** Returns a stub context object so slash commands and auto-save don't crash. */
363
+ /**
364
+ * Returns the context stand-in slash commands read. Reads are backed by the
365
+ * daemon's `stats` frames and the last `session_state` snapshot; writes stay
366
+ * no-ops because the conversation lives on the daemon (commands that would
367
+ * mutate it are refused in `commands.ts`, not faked here).
368
+ */
326
369
  getContext(): {
327
370
  saveCheckpoint(_label: string): void
328
371
  clear(): void
329
372
  getMessages(): Array<{ role: string; content: string }>
330
373
  getEstimatedTokens(): number
374
+ getMessageCount(): number
375
+ getMaxTokens(): number
376
+ getCompactionThreshold(): number
377
+ getCheckpoints(): unknown[]
378
+ getCacheStatus(): {
379
+ totalMessages: number
380
+ cachedMessages: number
381
+ cachedTokens: number
382
+ uncachedTokens: number
383
+ }
331
384
  } {
332
385
  return {
333
386
  saveCheckpoint: (_label: string) => {
@@ -336,8 +389,25 @@ export class RemoteEngine {
336
389
  clear: () => {
337
390
  // Remote mode: session history lives on the daemon
338
391
  },
339
- getMessages: () => [],
340
- getEstimatedTokens: () => 0,
392
+ getMessages: () => [...this.snapshotMessages],
393
+ getEstimatedTokens: () => this.stats?.estimatedTokens ?? 0,
394
+ // Exact when the daemon has reported; the snapshot is only the last 100.
395
+ getMessageCount: () => this.stats?.messageCount ?? this.snapshotMessages.length,
396
+ getMaxTokens: () => this.stats?.maxTokens ?? 0,
397
+ getCompactionThreshold: () => this.stats?.compactionThreshold ?? 0,
398
+ // Callers only read `.length`; the entries themselves have no reader here.
399
+ getCheckpoints: () =>
400
+ Array.from({ length: Math.max(0, this.stats?.checkpointCount ?? 0) }, () => undefined),
401
+ getCacheStatus: () => {
402
+ const estimated = this.stats?.estimatedTokens ?? 0
403
+ const cached = this.stats?.cachedTokens ?? 0
404
+ return {
405
+ totalMessages: this.stats?.messageCount ?? this.snapshotMessages.length,
406
+ cachedMessages: 0,
407
+ cachedTokens: cached,
408
+ uncachedTokens: Math.max(0, estimated - cached),
409
+ }
410
+ },
341
411
  }
342
412
  }
343
413
 
@@ -408,10 +478,17 @@ export class RemoteEngine {
408
478
  }
409
479
 
410
480
  /** Returns a stub registry so slash commands don't crash. */
411
- getRegistry(): { getProvider(_id: string): unknown; getProviders(): unknown[] } {
481
+ getRegistry(): {
482
+ getProvider(_id: string): unknown
483
+ getProviders(): unknown[]
484
+ healthMap(): Promise<Map<string, boolean>>
485
+ } {
412
486
  return {
413
487
  getProvider: (_id: string) => undefined,
414
488
  getProviders: () => [],
489
+ // `/status` awaits this. A registry stub without it crashes the command — the
490
+ // same shape as the missing context readers this file now backs with stats.
491
+ healthMap: async () => new Map<string, boolean>(),
415
492
  }
416
493
  }
417
494
 
@@ -451,9 +528,17 @@ export class RemoteEngine {
451
528
  return
452
529
  }
453
530
 
531
+ // Session readings, not prompt stream: local commands read them, and they must be
532
+ // absorbed even when nothing is consuming chunks.
533
+ if (msg.type === 'stats') {
534
+ this.absorbStats(msg)
535
+ return
536
+ }
537
+
454
538
  // Session facts, not prompt stream: they carry the gate's current mode and must be
455
539
  // absorbed even when nothing is consuming chunks (a keypress, not a turn).
456
540
  if (msg.type === 'mode' || msg.type === 'session_state') {
541
+ if (msg.type === 'session_state') this.absorbSnapshotMessages(msg.messages)
457
542
  // A snapshot describes the gate as of connect — see `absorbMode`.
458
543
  this.absorbMode(msg.mode, msg.type === 'session_state')
459
544
  return
@@ -516,6 +601,78 @@ export class RemoteEngine {
516
601
  * it is already superseded by a request that is in flight; the answer is what the footer
517
602
  * needs, and the daemon always sends one for a `set_mode` it understood.
518
603
  */
604
+ /**
605
+ * Merge one `stats` frame into the local readings.
606
+ *
607
+ * Per-field merge, not replace: a field the daemon did not send (older daemon,
608
+ * or one that omits a reader) keeps its previous value, and a malformed one is
609
+ * ignored. The alternative is a single `null` turning the footer into `NaN`.
610
+ */
611
+ private absorbStats(msg: ServerStatsMessage): void {
612
+ const num = (value: unknown): number | undefined =>
613
+ typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined
614
+ const patch = {
615
+ estimatedTokens: num(msg.estimatedTokens),
616
+ maxTokens: num(msg.maxTokens),
617
+ compactionThreshold: num(msg.compactionThreshold),
618
+ messageCount: num(msg.messageCount),
619
+ checkpointCount: num(msg.checkpointCount),
620
+ cachedTokens: num(msg.cachedTokens),
621
+ }
622
+ const current = this.stats ?? {
623
+ estimatedTokens: 0,
624
+ maxTokens: 0,
625
+ compactionThreshold: 0,
626
+ messageCount: 0,
627
+ checkpointCount: 0,
628
+ cachedTokens: 0,
629
+ }
630
+ this.stats = {
631
+ estimatedTokens: patch.estimatedTokens ?? current.estimatedTokens,
632
+ maxTokens: patch.maxTokens ?? current.maxTokens,
633
+ compactionThreshold: patch.compactionThreshold ?? current.compactionThreshold,
634
+ messageCount: patch.messageCount ?? current.messageCount,
635
+ checkpointCount: patch.checkpointCount ?? current.checkpointCount,
636
+ cachedTokens: patch.cachedTokens ?? current.cachedTokens,
637
+ }
638
+ }
639
+
640
+ /**
641
+ * Parse the snapshot's `MessageRecord[]` into the `{role, content}` shape local
642
+ * commands read. `content` is JSON-serialized on the daemon side; a record whose
643
+ * payload is not JSON is kept as plain text (a malformed record must not drop the
644
+ * whole snapshot).
645
+ */
646
+ private absorbSnapshotMessages(records: unknown): void {
647
+ if (!Array.isArray(records)) return
648
+ const parsed: Array<{ role: string; content: string }> = []
649
+ for (const record of records) {
650
+ if (typeof record !== 'object' || record === null) continue
651
+ const rec = record as Record<string, unknown>
652
+ let payload: unknown = rec.content
653
+ if (typeof payload === 'string') {
654
+ try {
655
+ payload = JSON.parse(payload)
656
+ } catch {
657
+ // Not JSON — treat the string itself as the content below.
658
+ }
659
+ }
660
+ const payloadRecord =
661
+ typeof payload === 'object' && payload !== null
662
+ ? (payload as Record<string, unknown>)
663
+ : null
664
+ const role =
665
+ typeof payloadRecord?.role === 'string'
666
+ ? payloadRecord.role
667
+ : typeof rec.role === 'string'
668
+ ? rec.role
669
+ : ''
670
+ if (role === '') continue
671
+ parsed.push({ role, content: contentToText(payloadRecord?.content ?? rec.content) })
672
+ }
673
+ this.snapshotMessages = parsed
674
+ }
675
+
519
676
  private absorbMode(mode: unknown, fromSnapshot = false): void {
520
677
  if (typeof mode !== 'string' || !ALL_MODES.includes(mode as PermissionMode)) return
521
678
  const effective = mode as PermissionMode
@@ -37,7 +37,7 @@ import { createDingtalkAdapter } from './dingtalk/adapter.js'
37
37
  import { createDingtalkApi } from './dingtalk/api.js'
38
38
  import type { DingtalkConfig } from './dingtalk/types.js'
39
39
  import { startHeartbeat } from './heartbeat'
40
- import { wireDaemonEngine } from './engine-capabilities'
40
+ import { wireDaemonEngine, attachDaemonSessionLog } from './engine-capabilities'
41
41
  import {
42
42
  cancelAllSessionTimers,
43
43
  unregisterWakeupHandler,
@@ -293,6 +293,18 @@ export function createServer(config: ServerConfig): Server<WsData> {
293
293
  cwd,
294
294
  registry: sharedRegistry,
295
295
  skillsPaths: daemonConfig.skills?.paths,
296
+ skillsReminder: daemonConfig.skills?.reminder,
297
+ })
298
+
299
+ // 审计日志必须在上面那次 DB 回灌**之后**挂 —— 它只记本进程窗口内发生的事,
300
+ // 镜像历史会在引擎重建时重复追加(WorkerPool 会驱逐空闲 worker)。
301
+ // 见 `attachDaemonSessionLog` 的三条约束。
302
+ attachDaemonSessionLog(engine, {
303
+ sessionId,
304
+ cwd,
305
+ provider,
306
+ model,
307
+ permissionMode: permission.getMode(),
296
308
  })
297
309
  engineCache.set(sessionId, engine)
298
310
  return engine
@@ -34,6 +34,7 @@ import type {
34
34
  ServerDoneMessage,
35
35
  ServerErrorMessage,
36
36
  ServerSessionStateMessage,
37
+ ServerStatsMessage,
37
38
  } from './attach-protocol'
38
39
 
39
40
  // ── Session State Snapshot ────────────────────────────────────────────────
@@ -89,6 +90,7 @@ export class SessionWorker {
89
90
  addClient(ws: ServerWebSocket<unknown>): void {
90
91
  this.clients.add(ws)
91
92
  this.sendState(ws)
93
+ this.sendStats(ws)
92
94
  }
93
95
 
94
96
  /** Remove a WebSocket client from this session's broadcast set. */
@@ -225,6 +227,9 @@ export class SessionWorker {
225
227
  stopReason,
226
228
  }
227
229
  this.broadcast(doneMsg)
230
+ // 一轮之后读数变了(消息、token、checkpoint)。命令在客户端本地跑,
231
+ // 它们读到的是**最近一帧**;不补这一帧,用户在下一轮前看到的永远是 attach 时的旧数。
232
+ this.broadcastStats()
228
233
 
229
234
  this.currentController = null
230
235
  this.processing = false
@@ -469,6 +474,51 @@ export class SessionWorker {
469
474
  }
470
475
  }
471
476
 
477
+ /**
478
+ * Read the engine's context numbers for a stats frame. Every reader is optional
479
+ * and guarded: the frame is advisory, and one engine (or one older checkout of
480
+ * the context) missing a reader must not take the whole turn down with it.
481
+ */
482
+ private buildStats(): Omit<ServerStatsMessage, 'type' | 'sessionId'> {
483
+ const ctx = this.engine.getContext()
484
+ const read = (fn: (() => number | undefined) | undefined): number => {
485
+ if (typeof fn !== 'function') return 0
486
+ try {
487
+ const value = fn()
488
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0
489
+ } catch {
490
+ return 0
491
+ }
492
+ }
493
+ return {
494
+ estimatedTokens: read(() => ctx.getEstimatedTokens?.()),
495
+ maxTokens: read(() => ctx.getMaxTokens?.()),
496
+ compactionThreshold: read(() => ctx.getCompactionThreshold?.()),
497
+ messageCount: read(() => ctx.getMessages?.().length),
498
+ checkpointCount: read(() => ctx.getCheckpoints?.().length),
499
+ cachedTokens: read(() => ctx.getCacheStatus?.().cachedTokens),
500
+ }
501
+ }
502
+
503
+ /** Send the current stats to one client (used right after its snapshot). */
504
+ private sendStats(ws: ServerWebSocket<unknown>): void {
505
+ const msg: ServerStatsMessage = {
506
+ type: 'stats',
507
+ sessionId: this.session.id,
508
+ ...this.buildStats(),
509
+ }
510
+ try {
511
+ ws.send(JSON.stringify(msg))
512
+ } catch {
513
+ this.clients.delete(ws)
514
+ }
515
+ }
516
+
517
+ /** Broadcast the current stats to every attached client. */
518
+ private broadcastStats(): void {
519
+ this.broadcast({ type: 'stats', sessionId: this.session.id, ...this.buildStats() })
520
+ }
521
+
472
522
  /** Build an error ServerMessage for the current session. */
473
523
  private errorMessage(message: string): ServerErrorMessage {
474
524
  return {
@@ -1,23 +1,35 @@
1
1
  import type { Locale } from './types'
2
2
  import { execSync } from 'node:child_process'
3
3
 
4
- export function detectLocale(opts?: { lang?: string; cwd?: string }): Locale {
4
+ export function detectLocale(opts?: {
5
+ lang?: string
6
+ /** The user's persisted `/lang` choice (read by the caller; see preference.ts). */
7
+ settingsLocale?: string | null
8
+ cwd?: string
9
+ }): Locale {
5
10
  // 1. CLI --lang flag
6
11
  if (opts?.lang) {
7
12
  const normalized = normalizeLocale(opts.lang)
8
13
  if (normalized) return normalized as Locale
9
14
  }
10
15
 
11
- // 2. LANG / LC_ALL env vars
16
+ // 2. Explicit user preference — beats the environment, or LANG=zh_CN would
17
+ // silently override someone who chose en-US.
18
+ if (opts?.settingsLocale) {
19
+ const normalized = normalizeLocale(opts.settingsLocale)
20
+ if (normalized) return normalized as Locale
21
+ }
22
+
23
+ // 3. LANG / LC_ALL env vars
12
24
  const langEnv = process.env.LC_ALL || process.env.LANG || ''
13
25
  const envLocale = parseLangEnv(langEnv)
14
26
  if (envLocale) return envLocale
15
27
 
16
- // 3. OS detection
28
+ // 4. OS detection
17
29
  const osLocale = detectOSLocale()
18
30
  if (osLocale) return osLocale
19
31
 
20
- // 4. Fallback
32
+ // 5. Fallback
21
33
  return 'en-US'
22
34
  }
23
35
 
@@ -265,11 +265,12 @@
265
265
  "confirmed": "✓ Rewound to checkpoint \"{label}\"\nRestored {count} messages.\n\nRemaining checkpoints: {remaining}\nUse /rewind again to go back further, or continue chatting."
266
266
  },
267
267
  "effort": {
268
- "usage": "Usage: /effort <level>\n\nSet reasoning effort level:\n low — Fast, simple tasks\n medium — Balanced quality and speed\n high — Thorough reasoning (default)\n xhigh — Maximum depth for coding/agentic use\n max — Absolute ceiling, very thorough\n\nCurrent model: {model}\nEffort levels require compatible providers (Anthropic Opus 4.6+, Sonnet 4.6).",
269
- "confirmed": "✓ Reasoning effort set to \"{level}\""
268
+ "usage": "Usage: /effort <level>\n\nSets the streaming stall budget — how long a silent stream may run before it is\ntreated as dead. It does NOT change how hard the model reasons:\n low — 90s idle budget\n medium — 90s\n high — 180s\n xhigh — 270s\n max — 360s\n\nCurrent model: {model}",
269
+ "confirmed": "✓ Stream stall budget set to \"{level}\" (timeout only — reasoning depth comes from the provider/model)"
270
270
  },
271
271
  "focus": {
272
- "on": "✓ Focus mode ON — showing only the most recent exchange.\nPrevious messages are hidden but preserved.\nType /focus again to exit focus mode and show all messages."
272
+ "on": "✓ Focus mode ON — showing only the most recent exchange.\nPrevious messages are hidden but preserved.\nType /focus again to exit focus mode and show all messages.",
273
+ "off": "✓ Focus mode OFF — showing all messages."
273
274
  },
274
275
  "ultracode": {
275
276
  "on": "✓ Ultracode mode ON — multi-agent workflow orchestration enabled.\n\nThe AI will use Workflow tool to fan out, verify, and synthesize for all substantive tasks.",
@@ -279,7 +280,7 @@
279
280
  "branch": {
280
281
  "no_conversation": "No conversation to branch. Start a conversation first.",
281
282
  "title": "── Branch Created ──",
282
- "details": "Name: \"{name}\"\nCheckpoint: #{checkpoint}\nMessages: {messages} saved\n\nCurrent conversation continues from this point.\nTo return to this branch point later, use:\n /rewind\n\nNote: Full session branching (separate concurrent sessions) requires session persistence, coming in a future release. For now, this saves a named checkpoint you can rewind to."
283
+ "details": "Name: \"{name}\"\nCheckpoint: #{checkpoint}\nMessages: {messages} saved\n\nCurrent conversation continues from this point.\nTo return to this branch point later, use:\n /rewind\n\nNote: this saves a named checkpoint you can rewind to. It does not create a separate concurrent session — Mipham Code has no such mode today."
283
284
  },
284
285
  "memories": {
285
286
  "title": "─ Memory ─",
@@ -325,7 +326,7 @@
325
326
  "unverified": "⚠ Installed, but could not verify the new version: {reason}"
326
327
  },
327
328
  "no_plan": {
328
- "confirmed": "✓ Plan mode exited. Your plan has been discarded.\n\nContinue chatting as normal, or type /plan to start a new plan."
329
+ "confirmed": "✓ Plan mode exited. Your plan was not applied (the plan file is kept for reference).\n\nContinue chatting as normal, or type /plan to start a new plan."
329
330
  },
330
331
  "mcp": {
331
332
  "usage_connect": "Usage: /mcp connect <server-name>",
@@ -481,6 +482,7 @@
481
482
  "source_user": "user",
482
483
  "source_project": "project",
483
484
  "gated": "⚠️ workspace not trusted — will not run",
485
+ "undispatched": "⚠️ no dispatch point in this version — will not run",
484
486
  "found": "{count} hook(s) found.",
485
487
  "error": "── Hooks ──\n\nCould not read hooks directory."
486
488
  },
@@ -265,11 +265,12 @@
265
265
  "confirmed": "✓ 已回退到检查点 \"{label}\"\n已恢复 {count} 条消息。\n\n剩余检查点: {remaining}\n再次使用 /rewind 继续回退,或继续对话。"
266
266
  },
267
267
  "effort": {
268
- "usage": "用法: /effort <level>\n\n设置推理深度:\n low — 快速、简单任务\n medium — 质量与速度平衡\n high — 深入推理(默认)\n xhigh — 编码/Agent 最大深度\n max — 绝对上限,非常彻底\n\n当前模型: {model}\n推理深度需要兼容的提供商(Anthropic Opus 4.6+, Sonnet 4.6)。",
269
- "confirmed": "✓ 推理深度设置为 \"{level}\""
268
+ "usage": "用法: /effort <level>\n\n设置流式空闲预算 —— 流静默多久后被判定为断流。它不改变模型的推理深度:\n low — 90 秒空闲预算\n medium — 90 秒\n high — 180 秒\n xhigh — 270 秒\n max — 360 秒\n\n当前模型: {model}",
269
+ "confirmed": "✓ 流式空闲预算已设为 \"{level}\"(仅超时;推理深度由提供商/模型决定)"
270
270
  },
271
271
  "focus": {
272
- "on": "✓ 聚焦模式已开启 — 仅显示最近一次交流。\n之前的消息已隐藏但保留。\n再次输入 /focus 退出聚焦模式并显示所有消息。"
272
+ "on": "✓ 聚焦模式已开启 — 仅显示最近一次交流。\n之前的消息已隐藏但保留。\n再次输入 /focus 退出聚焦模式并显示所有消息。",
273
+ "off": "✓ 聚焦模式已关闭 — 显示所有消息。"
273
274
  },
274
275
  "ultracode": {
275
276
  "on": "✓ Ultracode 模式已开启 — 多 Agent 工作流编排已启用。\n\nAI 将使用 Workflow 工具对所有实质性任务进行分发、验证和综合。",
@@ -279,7 +280,7 @@
279
280
  "branch": {
280
281
  "no_conversation": "没有可分支的对话。请先开始对话。",
281
282
  "title": "── 分支已创建 ──",
282
- "details": "名称: \"{name}\"\n检查点: #{checkpoint}\n消息: {messages} 已保存\n\n当前对话从此刻继续。\n以后返回此分支点,使用:\n /rewind\n\n注意: 完整会话分支(单独的并发会话)需要会话持久化,将在未来版本中提供。目前这会保存一个可回退的命名检查点。"
283
+ "details": "名称: \"{name}\"\n检查点: #{checkpoint}\n消息: {messages} 已保存\n\n当前对话从此刻继续。\n以后返回此分支点,使用:\n /rewind\n\n注意: 这会保存一个可回退的命名检查点,不会创建独立的并发会话 —— 目前没有这种模式。"
283
284
  },
284
285
  "memories": {
285
286
  "title": "─ 记忆 ─",
@@ -325,7 +326,7 @@
325
326
  "unverified": "⚠ 已安装,但无法验证新版本: {reason}"
326
327
  },
327
328
  "no_plan": {
328
- "confirmed": "✓ 计划模式已退出。你的计划已丢弃。\n\n继续正常对话,或输入 /plan 开始新计划。"
329
+ "confirmed": "✓ 计划模式已退出。计划未被执行(计划文件仍保留供参考)。\n\n继续正常对话,或输入 /plan 开始新计划。"
329
330
  },
330
331
  "mcp": {
331
332
  "usage_connect": "用法: /mcp connect <server-name>",
@@ -481,6 +482,7 @@
481
482
  "source_user": "用户级",
482
483
  "source_project": "项目级",
483
484
  "gated": "⚠️ 工作区未受信任,不会运行",
485
+ "undispatched": "⚠️ 本版本没有派发点,不会运行",
484
486
  "found": "找到 {count} 个钩子。",
485
487
  "error": "── 钩子 ──\n\n无法读取钩子目录。"
486
488
  },
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The user's persisted locale choice (`/lang`).
3
+ *
4
+ * Lives in `~/.mipham/settings.json` — the same file telemetry consent uses —
5
+ * because it is the only config writer that preserves keys it does not model.
6
+ * `detectLocale` reads this before `LANG`, so an explicit choice is not
7
+ * overridden by the shell's environment on the next start.
8
+ */
9
+ import { mkdirSync } from 'node:fs'
10
+ import { dirname } from 'node:path'
11
+ import { atomicWriteFileSync } from '../shared/atomic-write'
12
+ import { readRegularFileSync } from '../shared/regular-file'
13
+ import { miphamHome } from '../core/paths.ts'
14
+ import { SUPPORTED_LOCALES, type Locale } from './types'
15
+
16
+ function settingsPath(): string {
17
+ return miphamHome('settings.json')
18
+ }
19
+
20
+ /** The saved locale, or null when absent / unsupported / unreadable. */
21
+ export function readLocalePreference(): Locale | null {
22
+ try {
23
+ const raw = readRegularFileSync(settingsPath())
24
+ if (raw === null) return null
25
+ const parsed: unknown = JSON.parse(raw)
26
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null
27
+ const value = (parsed as { locale?: unknown }).locale
28
+ return typeof value === 'string' && (SUPPORTED_LOCALES as string[]).includes(value)
29
+ ? (value as Locale)
30
+ : null
31
+ } catch {
32
+ return null
33
+ }
34
+ }
35
+
36
+ /** Persist the choice, preserving unrelated keys. Returns false on write failure. */
37
+ export function saveLocalePreference(locale: Locale): boolean {
38
+ try {
39
+ let doc: Record<string, unknown> = {}
40
+ const raw = readRegularFileSync(settingsPath())
41
+ if (raw !== null) {
42
+ const parsed: unknown = JSON.parse(raw)
43
+ if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
44
+ doc = parsed as Record<string, unknown>
45
+ }
46
+ }
47
+ doc.locale = locale
48
+ const path = settingsPath()
49
+ mkdirSync(dirname(path), { recursive: true })
50
+ atomicWriteFileSync(path, JSON.stringify(doc, null, 2) + '\n', { mode: 0o644 })
51
+ return true
52
+ } catch {
53
+ return false
54
+ }
55
+ }
package/src/index.tsx CHANGED
@@ -73,6 +73,7 @@ import { AgentViewManager } from './agent-view/agent-view-manager'
73
73
  import { AgentsStandalone } from './agent-view/agents-standalone'
74
74
  import { createT } from './i18n-core/t'
75
75
  import { detectLocale } from './i18n-core/detect'
76
+ import { readLocalePreference } from './i18n-core/preference'
76
77
  import { I18nProvider } from './i18n-context'
77
78
  import { ConfigWizard } from './ui/config-wizard'
78
79
  import enUS from './i18n-core/locales/en-US.json' with { type: 'json' }
@@ -374,7 +375,7 @@ export async function runApp(options: RunOptions): Promise<void> {
374
375
  if (options.permission) engine.getPermission().setMode(options.permission)
375
376
 
376
377
  // Detect locale and create translation function (same as local path)
377
- const locale = detectLocale({ lang: options.lang })
378
+ const locale = detectLocale({ lang: options.lang, settingsLocale: readLocalePreference() })
378
379
  const t = createT(localeBundles[locale] || enUS, enUS)
379
380
 
380
381
  // Set terminal window title
@@ -493,7 +494,7 @@ export async function runApp(options: RunOptions): Promise<void> {
493
494
  }
494
495
 
495
496
  // Detect locale and create translation function
496
- const locale = detectLocale({ lang: options.lang })
497
+ const locale = detectLocale({ lang: options.lang, settingsLocale: readLocalePreference() })
497
498
  const t = createT(localeBundles[locale] || enUS, enUS)
498
499
 
499
500
  // Bootstrap providers
@@ -52,6 +52,30 @@ function isPlainObject(value: unknown): value is Record<string, unknown> {
52
52
  return typeof value === 'object' && value !== null && !Array.isArray(value)
53
53
  }
54
54
 
55
+ function hasProperties(node: Record<string, unknown>): boolean {
56
+ return isPlainObject(node.properties) && Object.keys(node.properties).length > 0
57
+ }
58
+
59
+ /**
60
+ * A server may put the union at the root (`anyOf`/`oneOf`). Reading only
61
+ * `root.properties` made that tool reach the model with **no parameters at
62
+ * all** — callable, but every argument invisible. Follow the first branch that
63
+ * declares properties (nested unions included); keep the root when it declares
64
+ * properties itself, so a schema that has both is not rewritten.
65
+ */
66
+ function schemaWithProperties(schema: unknown, depth = 0): Record<string, unknown> {
67
+ const node = isPlainObject(schema) ? schema : {}
68
+ if (hasProperties(node) || depth >= 8) return node
69
+ const branches = (
70
+ Array.isArray(node.anyOf) ? node.anyOf : Array.isArray(node.oneOf) ? node.oneOf : []
71
+ ).filter(isPlainObject)
72
+ for (const branch of branches) {
73
+ const resolved = schemaWithProperties(branch, depth + 1)
74
+ if (hasProperties(resolved)) return resolved
75
+ }
76
+ return branches[0] ?? node
77
+ }
78
+
55
79
  /**
56
80
  * Coerce a server-declared `inputSchema` into a shape every provider accepts.
57
81
  *
@@ -61,12 +85,16 @@ function isPlainObject(value: unknown): value is Record<string, unknown> {
61
85
  * unusable — not just the one tool. Only the top level is repaired: property
62
86
  * schemas that are themselves objects are kept verbatim, so this narrows
63
87
  * malformed input without rewriting a server's intent.
88
+ *
89
+ * A root-level `anyOf`/`oneOf` is not malformed, but it is a shape no provider
90
+ * accepts as tool parameters — the first branch that declares properties is
91
+ * surfaced instead of dropping the tool's whole argument surface.
64
92
  */
65
93
  export function sanitizeInputSchema(schema: unknown): {
66
94
  properties: Record<string, unknown>
67
95
  required?: string[]
68
96
  } {
69
- const root = isPlainObject(schema) ? schema : {}
97
+ const root = schemaWithProperties(schema)
70
98
  const rawProperties = isPlainObject(root.properties) ? root.properties : {}
71
99
  const properties: Record<string, unknown> = {}
72
100
  for (const [name, property] of Object.entries(rawProperties)) {
@@ -9,7 +9,7 @@
9
9
  export const PACKAGE_NAME = '@miphamai/cli' as const
10
10
 
11
11
  /** 当前发布版本 */
12
- export const PACKAGE_VERSION = '0.85.34' as const
12
+ export const PACKAGE_VERSION = '0.85.36' as const
13
13
 
14
14
  /** npm install 全局安装命令 */
15
15
  export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
@@ -75,7 +75,7 @@ export const COMPANY_SHORT = '华安麦逄科技' as const
75
75
  */
76
76
 
77
77
  /** Slash 命令总数(真源:`getCommandNames().length`,`apps/cli/src/ui/commands.ts`) */
78
- export const SLASH_COMMAND_COUNT = 138 as const
78
+ export const SLASH_COMMAND_COUNT = 139 as const
79
79
 
80
80
  /** 内置提供商总数(真源:`DEFAULT_PROVIDERS.length`,`apps/cli/src/shared/constants.ts`) */
81
81
  export const PROVIDER_COUNT = 12 as const
@@ -90,4 +90,4 @@ export const TOOL_COUNT = 31 as const
90
90
  * —— `test/e2e/full-pipeline.test.ts` 在 Linux 上整文件 skip、在 macOS 上跑 ——
91
91
  * 但**总数相同**(两边都把被 skip 的算进去)。
92
92
  */
93
- export const TEST_COUNT = 4807 as const
93
+ export const TEST_COUNT = 4928 as const