@miphamai/cli 0.85.35 → 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.
- package/README.md +4 -4
- package/package.json +1 -1
- package/src/commands/environment.ts +53 -69
- package/src/commands/git.ts +53 -16
- package/src/commands/keys.ts +28 -17
- package/src/commands/project.ts +10 -17
- package/src/commands/workflow-view.ts +24 -6
- package/src/core/engine.ts +29 -2
- package/src/core/improvement-track.ts +37 -1
- package/src/core/meta-rule-engine.ts +3 -1
- package/src/core/rule-engine.ts +11 -5
- package/src/core/task-performance.ts +41 -0
- package/src/daemon/attach-protocol.ts +25 -0
- package/src/daemon/remote-engine.ts +161 -4
- package/src/daemon/session-worker.ts +50 -0
- package/src/i18n-core/detect.ts +16 -4
- package/src/i18n-core/locales/en-US.json +6 -5
- package/src/i18n-core/locales/zh-CN.json +6 -5
- package/src/i18n-core/preference.ts +55 -0
- package/src/index.tsx +3 -2
- package/src/mcp/registry.ts +29 -1
- package/src/shared/package-info.ts +3 -3
- package/src/tools/exec/git.ts +82 -0
- package/src/ui/app.tsx +26 -19
- package/src/ui/commands.ts +514 -98
- package/src/ui/strip-indent.ts +9 -4
|
@@ -68,6 +68,35 @@ export interface TaskPerformanceResult {
|
|
|
68
68
|
truncated?: boolean
|
|
69
69
|
}
|
|
70
70
|
|
|
71
|
+
/** 空模型闸的读数:`passed` = 空程序也能通过的题数。 */
|
|
72
|
+
export interface NullModelCheck {
|
|
73
|
+
total: number
|
|
74
|
+
passed: number
|
|
75
|
+
/** 空程序也通过的题 id —— 它们正是这道闸抓到的「不是模型题」的题。 */
|
|
76
|
+
failures: string[]
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 空模型消融:对每道题只用**空程序**跑冻结测试。
|
|
81
|
+
*
|
|
82
|
+
* 来源是自改进研究的 null-model control:把模型换成空 stub 重跑,分数仍涨就说明
|
|
83
|
+
* 「改进」不是模型带来的。在我们的架构里模型不产出 ⇒ 空程序;能通过,就说明这道
|
|
84
|
+
* 题测的是测试自身的空转(例如恒真断言),不是模型能力。
|
|
85
|
+
*/
|
|
86
|
+
export function countEmptySolutionPasses(tasks: PerformanceTask[]): NullModelCheck {
|
|
87
|
+
const failures: string[] = []
|
|
88
|
+
for (const task of tasks) {
|
|
89
|
+
if (judgeGeneratedCode(task.testCode, '').passed) failures.push(task.id)
|
|
90
|
+
}
|
|
91
|
+
return { total: tasks.length, passed: failures.length, failures }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** 按 skill 名取任务集再跑空模型闸;未绑定任何任务的 skill → total 0(空转,不是通过)。 */
|
|
95
|
+
export function runNullModelCheck(skill?: string): NullModelCheck {
|
|
96
|
+
const tasks = loadPerformanceTasks().filter((t) => (t.skill ?? undefined) === skill)
|
|
97
|
+
return countEmptySolutionPasses(tasks)
|
|
98
|
+
}
|
|
99
|
+
|
|
71
100
|
export interface TaskPerformanceReport {
|
|
72
101
|
total: number
|
|
73
102
|
passed: number
|
|
@@ -242,6 +271,13 @@ export interface SkillDeltaSample {
|
|
|
242
271
|
skillName: string
|
|
243
272
|
baselineScores: number[]
|
|
244
273
|
postScores: number[]
|
|
274
|
+
/**
|
|
275
|
+
* 空模型闸:把**空程序**喂给同一组冻结测试,通过的题数。
|
|
276
|
+
* 通过 > 0 ⇒ 这些题空程序也能过,测的不是模型能力 ⇒ 改进判定不可归因。
|
|
277
|
+
* 缺席 = 旧记录 / 未测(与 nullModelTotal 同生同灭)。
|
|
278
|
+
*/
|
|
279
|
+
nullModelPassed?: number
|
|
280
|
+
nullModelTotal?: number
|
|
245
281
|
/**
|
|
246
282
|
* B2 代价维:与分数数组**逐项对齐**的耗时(第 i 项就是产出第 i 个分数的那次采样)。
|
|
247
283
|
* 缺席 = 该样本未记代价(旧记录 / 旧调用点),读侧须按「缺席」处理、不得当成 0。
|
|
@@ -283,11 +319,16 @@ export async function measureSkillDeltaRepeated(
|
|
|
283
319
|
postDurations.push(r.durationMs)
|
|
284
320
|
}
|
|
285
321
|
|
|
322
|
+
// 空模型闸在最后一次采样后算一次:与模型无关,重复跑只是重复同一组测试。
|
|
323
|
+
const nullCheck = runNullModelCheck(resolved.skillName)
|
|
324
|
+
|
|
286
325
|
return {
|
|
287
326
|
skillName: resolved.skillName,
|
|
288
327
|
baselineScores,
|
|
289
328
|
postScores,
|
|
290
329
|
baselineDurations,
|
|
291
330
|
postDurations,
|
|
331
|
+
nullModelPassed: nullCheck.passed,
|
|
332
|
+
nullModelTotal: nullCheck.total,
|
|
292
333
|
}
|
|
293
334
|
}
|
|
@@ -88,6 +88,30 @@ export interface ServerModeMessage {
|
|
|
88
88
|
sessionId: string
|
|
89
89
|
mode: PermissionMode
|
|
90
90
|
}
|
|
91
|
+
/**
|
|
92
|
+
* 会话读数(daemon → 客户端)。`attach` 的本地 `getContext()` 是个薄桩,
|
|
93
|
+
* `/status`、`/cost`、`/doctor` 这类只读命令要用到的 token / 窗口 / checkpoint
|
|
94
|
+
* 数都在 daemon 手里 —— 由这一帧送过来,客户端据此作答,而不是显示一排 0。
|
|
95
|
+
*
|
|
96
|
+
* 每个字段都按「daemon 可能没送」处理:两端版本独立,缺字段或类型不对时客户端
|
|
97
|
+
* 保持原值(不拿 NaN 去渲染)。
|
|
98
|
+
*/
|
|
99
|
+
export interface ServerStatsMessage {
|
|
100
|
+
type: 'stats'
|
|
101
|
+
sessionId: string
|
|
102
|
+
/** 引擎上下文当前的估算 token 数。 */
|
|
103
|
+
estimatedTokens: number
|
|
104
|
+
/** 模型上下文窗口。 */
|
|
105
|
+
maxTokens: number
|
|
106
|
+
/** 触发压缩的阈值(token)。 */
|
|
107
|
+
compactionThreshold: number
|
|
108
|
+
/** 引擎上下文里的消息数。 */
|
|
109
|
+
messageCount: number
|
|
110
|
+
/** 本会话已保存的 checkpoint 数。 */
|
|
111
|
+
checkpointCount: number
|
|
112
|
+
/** 当前由 provider prompt cache 提供的 token 数。 */
|
|
113
|
+
cachedTokens: number
|
|
114
|
+
}
|
|
91
115
|
|
|
92
116
|
export type ServerMessage =
|
|
93
117
|
| ServerTextMessage
|
|
@@ -99,3 +123,4 @@ export type ServerMessage =
|
|
|
99
123
|
| ServerErrorMessage
|
|
100
124
|
| ServerSessionStateMessage
|
|
101
125
|
| ServerModeMessage
|
|
126
|
+
| ServerStatsMessage
|
|
@@ -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
|
-
/**
|
|
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(): {
|
|
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
|
|
@@ -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 {
|
package/src/i18n-core/detect.ts
CHANGED
|
@@ -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?: {
|
|
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.
|
|
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
|
-
//
|
|
28
|
+
// 4. OS detection
|
|
17
29
|
const osLocale = detectOSLocale()
|
|
18
30
|
if (osLocale) return osLocale
|
|
19
31
|
|
|
20
|
-
//
|
|
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\
|
|
269
|
-
"confirmed": "✓
|
|
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:
|
|
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
|
|
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>",
|
|
@@ -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
|
|
269
|
-
"confirmed": "✓
|
|
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": "✓
|
|
329
|
+
"confirmed": "✓ 计划模式已退出。计划未被执行(计划文件仍保留供参考)。\n\n继续正常对话,或输入 /plan 开始新计划。"
|
|
329
330
|
},
|
|
330
331
|
"mcp": {
|
|
331
332
|
"usage_connect": "用法: /mcp connect <server-name>",
|
|
@@ -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
|
package/src/mcp/registry.ts
CHANGED
|
@@ -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 =
|
|
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)) {
|