@miphamai/cli 0.85.52 → 0.85.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,262 @@
1
+ /**
2
+ * Cross-session insight report — counts only.
3
+ *
4
+ * Reads the CLI's own session logs (`~/.mipham/sessions/*.jsonl`) and produces
5
+ * an aggregate report. Deliberately never prints message text, tool input or
6
+ * tool output: the point is "where did my tool calls go", not a transcript.
7
+ *
8
+ * Counting rule that is easy to get wrong: `messageToEvents` splits a tool
9
+ * call/result out of a message only when that message holds a **single**
10
+ * block; a multi-block turn stays one `assistant/message` / `user/message`.
11
+ * Counting event types alone therefore under-reports tool calls and failures,
12
+ * so both shapes are counted here.
13
+ */
14
+
15
+ import { readdirSync, readFileSync, statSync } from 'node:fs'
16
+ import { join } from 'node:path'
17
+ import { interruptedCallNotice, isValidEvent, type SessionEvent } from './session-log'
18
+ import { miphamHome } from './paths.ts'
19
+
20
+ export interface SessionInsightsInput {
21
+ name: string
22
+ events: SessionEvent[]
23
+ }
24
+
25
+ export interface InsightsReport {
26
+ sessions: number
27
+ events: number
28
+ userMessages: number
29
+ assistantMessages: number
30
+ toolCalls: number
31
+ toolFailures: number
32
+ toolUnknown: number
33
+ compactions: number
34
+ topTools: Array<{ name: string; count: number }>
35
+ models: Array<{ provider: string; model: string; count: number }>
36
+ firstAt: number | null
37
+ lastAt: number | null
38
+ }
39
+
40
+ export interface LoadedSessionLogs {
41
+ inputs: SessionInsightsInput[]
42
+ skippedFiles: number
43
+ skippedLines: number
44
+ }
45
+
46
+ const DEFAULT_MAX_FILES = 200
47
+ const DEFAULT_MAX_BYTES = 20 * 1024 * 1024
48
+ const DEFAULT_MAX_TOTAL_BYTES = 64 * 1024 * 1024
49
+
50
+ /** Aggregate the already-parsed events. Pure: no I/O, deterministic. */
51
+ export function summarizeSessions(inputs: SessionInsightsInput[]): InsightsReport {
52
+ const topTools = new Map<string, number>()
53
+ const models = new Map<string, { provider: string; model: string; count: number }>()
54
+ const interrupted = interruptedCallNotice()
55
+
56
+ let events = 0
57
+ let userMessages = 0
58
+ let assistantMessages = 0
59
+ let toolCalls = 0
60
+ let toolFailures = 0
61
+ let toolUnknown = 0
62
+ let compactions = 0
63
+ let firstAt: number | null = null
64
+ let lastAt: number | null = null
65
+
66
+ const bumpTool = (name: unknown) => {
67
+ toolCalls += 1
68
+ // A `tool_use` block with no `name` is legal on disk (the provider emits a
69
+ // synthetic name only later), and older logs can carry one. Keying the map
70
+ // with `undefined` made the tie-break sort below call `localeCompare` on it
71
+ // and throw — `/insights` failed on the whole log instead of counting the
72
+ // call (CC 2.1.334-093).
73
+ const key = typeof name === 'string' && name.length > 0 ? name : '(unnamed tool)'
74
+ topTools.set(key, (topTools.get(key) ?? 0) + 1)
75
+ }
76
+
77
+ for (const input of inputs) {
78
+ for (const event of input.events) {
79
+ events += 1
80
+ if (Number.isFinite(event.at) && event.at > 0) {
81
+ firstAt = firstAt === null ? event.at : Math.min(firstAt, event.at)
82
+ lastAt = lastAt === null ? event.at : Math.max(lastAt, event.at)
83
+ }
84
+
85
+ switch (event.type) {
86
+ case 'user/message': {
87
+ userMessages += 1
88
+ if (Array.isArray(event.message.content)) {
89
+ for (const block of event.message.content) {
90
+ if (block.type === 'tool_result' && block.is_error === true) toolFailures += 1
91
+ }
92
+ }
93
+ break
94
+ }
95
+ case 'assistant/message': {
96
+ assistantMessages += 1
97
+ if (Array.isArray(event.message.content)) {
98
+ for (const block of event.message.content) {
99
+ if (block.type === 'tool_use') bumpTool(block.name)
100
+ }
101
+ }
102
+ break
103
+ }
104
+ case 'tool/call':
105
+ bumpTool(event.name)
106
+ break
107
+ case 'tool/result':
108
+ if (event.result.success === false) {
109
+ // Synthesized on resume for calls that were in flight when the
110
+ // process died — "outcome unknown" is not the same as "failed".
111
+ if (event.result.content === interrupted) toolUnknown += 1
112
+ else toolFailures += 1
113
+ }
114
+ break
115
+ case 'compaction/summary':
116
+ compactions += 1
117
+ break
118
+ case 'session/start': {
119
+ const provider = event.provider ?? 'unknown'
120
+ const model = event.model ?? 'unknown'
121
+ const key = `${provider}\u0000${model}`
122
+ const seen = models.get(key)
123
+ if (seen) seen.count += 1
124
+ else models.set(key, { provider, model, count: 1 })
125
+ break
126
+ }
127
+ default:
128
+ break
129
+ }
130
+ }
131
+ }
132
+
133
+ return {
134
+ sessions: inputs.length,
135
+ events,
136
+ userMessages,
137
+ assistantMessages,
138
+ toolCalls,
139
+ toolFailures,
140
+ toolUnknown,
141
+ compactions,
142
+ topTools: [...topTools.entries()]
143
+ .map(([name, count]) => ({ name, count }))
144
+ .sort((a, b) => b.count - a.count || a.name.localeCompare(b.name))
145
+ .slice(0, 10),
146
+ models: [...models.values()].sort(
147
+ (a, b) =>
148
+ b.count - a.count || `${a.provider}/${a.model}`.localeCompare(`${b.provider}/${b.model}`),
149
+ ),
150
+ firstAt,
151
+ lastAt,
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Read session logs newest-first with hard budgets, so one pathological
157
+ * directory cannot turn a slash command into a multi-GB synchronous read.
158
+ */
159
+ export function loadSessionLogs(
160
+ dir: string = miphamHome('sessions'),
161
+ opts: { maxFiles?: number; maxBytes?: number; maxTotalBytes?: number } = {},
162
+ ): LoadedSessionLogs {
163
+ const maxFiles = opts.maxFiles ?? DEFAULT_MAX_FILES
164
+ const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES
165
+ const maxTotalBytes = opts.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES
166
+
167
+ const inputs: SessionInsightsInput[] = []
168
+ let skippedFiles = 0
169
+ let skippedLines = 0
170
+
171
+ let names: string[]
172
+ try {
173
+ names = readdirSync(dir).filter((name) => name.endsWith('.jsonl'))
174
+ } catch {
175
+ return { inputs, skippedFiles, skippedLines }
176
+ }
177
+
178
+ const files: Array<{ name: string; mtimeMs: number; size: number }> = []
179
+ for (const name of names) {
180
+ try {
181
+ const st = statSync(join(dir, name))
182
+ files.push({ name, mtimeMs: st.mtimeMs, size: st.size })
183
+ } catch {
184
+ skippedFiles += 1
185
+ }
186
+ }
187
+
188
+ files.sort((a, b) => b.mtimeMs - a.mtimeMs)
189
+ const selected = files.slice(0, maxFiles)
190
+ skippedFiles += files.length - selected.length
191
+
192
+ let totalBytes = 0
193
+ for (const file of selected) {
194
+ if (file.size > maxBytes || totalBytes + file.size > maxTotalBytes) {
195
+ skippedFiles += 1
196
+ continue
197
+ }
198
+ totalBytes += file.size
199
+
200
+ try {
201
+ const raw = readFileSync(join(dir, file.name), 'utf-8')
202
+ const events: SessionEvent[] = []
203
+ for (const line of raw.split('\n')) {
204
+ const text = line.trim()
205
+ if (!text) continue
206
+ try {
207
+ const parsed: unknown = JSON.parse(text)
208
+ if (isValidEvent(parsed)) events.push(parsed)
209
+ else skippedLines += 1
210
+ } catch {
211
+ skippedLines += 1
212
+ }
213
+ }
214
+ inputs.push({ name: file.name, events })
215
+ } catch {
216
+ skippedFiles += 1
217
+ }
218
+ }
219
+
220
+ return { inputs, skippedFiles, skippedLines }
221
+ }
222
+
223
+ export function formatInsightsReport(
224
+ report: InsightsReport,
225
+ dir: string,
226
+ loaded: { skippedFiles: number; skippedLines: number },
227
+ ): string {
228
+ if (report.sessions === 0) {
229
+ return `No session logs found at ${dir}.`
230
+ }
231
+
232
+ const range =
233
+ report.firstAt !== null && report.lastAt !== null
234
+ ? `${new Date(report.firstAt).toISOString()} → ${new Date(report.lastAt).toISOString()}`
235
+ : 'unknown'
236
+
237
+ const lines: string[] = [
238
+ '── Session Insights ──',
239
+ `Scanned: ${dir} (${report.sessions} sessions, ${report.events} events)`,
240
+ '',
241
+ `Messages: user ${report.userMessages} · assistant ${report.assistantMessages}`,
242
+ `Tool calls: ${report.toolCalls} (failures ${report.toolFailures}, unknown ${report.toolUnknown})`,
243
+ `Compactions: ${report.compactions}`,
244
+ `Range: ${range}`,
245
+ ]
246
+
247
+ if (report.models.length > 0) {
248
+ lines.push('', 'Models:')
249
+ for (const m of report.models) lines.push(` ${m.provider}/${m.model} ${m.count}`)
250
+ }
251
+
252
+ if (report.topTools.length > 0) {
253
+ lines.push('', 'Top tools:')
254
+ for (const t of report.topTools) lines.push(` ${t.name} ${t.count}`)
255
+ }
256
+
257
+ if (loaded.skippedFiles > 0 || loaded.skippedLines > 0) {
258
+ lines.push('', `Skipped: ${loaded.skippedFiles} file(s), ${loaded.skippedLines} line(s).`)
259
+ }
260
+
261
+ return lines.join('\n')
262
+ }
@@ -177,7 +177,7 @@ function endsWithNewline(path: string): boolean {
177
177
  }
178
178
 
179
179
  /** 补上的那条结果的正文:说明事情本身,并给出下一步,而不是只报一个状态。 */
180
- function interruptedCallNotice(): string {
180
+ export function interruptedCallNotice(): string {
181
181
  return (
182
182
  `This tool call was in flight when the session ended, so its outcome is unknown — ` +
183
183
  `the result was never recorded.\n` +
@@ -424,7 +424,7 @@ export function isValidMessage(m: unknown): boolean {
424
424
  * 不校验 `session/start`、`assistant/chunk`、`checker/decision`:投影对它们无分支;
425
425
  * 未知类型一律放行(前向兼容 —— 认不出来不等于要销毁它)。
426
426
  */
427
- function isValidEvent(e: unknown): e is SessionEvent {
427
+ export function isValidEvent(e: unknown): e is SessionEvent {
428
428
  if (!e || typeof e !== 'object') return false
429
429
  const ev = e as Record<string, unknown>
430
430
  if (typeof ev.type !== 'string') return false
@@ -415,8 +415,14 @@ export class SessionStore {
415
415
  static getLatest(): SessionIndexEntry | null {
416
416
  const index = SessionStore.loadIndexRaw()
417
417
  if (index.length > 0) {
418
- index.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())
419
- return index[0]!
418
+ // A session that has only `session/start` (opened, then exited without a
419
+ // turn) is not something `/resume last` or `--continue` can continue. It
420
+ // used to become the newest entry and hide the real previous turn; skip
421
+ // it (CC 2.1.335-067). `undefined` is kept: older indexes predate the field.
422
+ const resumable = index.filter((entry) => entry.messageCount !== 0)
423
+ if (resumable.length === 0) return null
424
+ resumable.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())
425
+ return resumable[0]!
420
426
  }
421
427
  // Fallback: scan .jsonl files directly when index is missing
422
428
  return SessionStore.scanLatestFromDisk()
@@ -425,29 +431,30 @@ export class SessionStore {
425
431
  /** Scan .jsonl files on disk by mtime — fallback when .index.json is missing. */
426
432
  private static scanLatestFromDisk(): SessionIndexEntry | null {
427
433
  ensureDir()
428
- const files = readdirSync(SESSIONS_DIR).filter((f) => f.endsWith('.jsonl'))
429
- if (files.length === 0) return null
430
- let latest: { name: string; mtime: number } | null = null
431
- for (const file of files) {
432
- const stat = statSync(join(SESSIONS_DIR, file))
433
- if (!latest || stat.mtimeMs > latest.mtime) {
434
- latest = { name: file.replace('.jsonl', ''), mtime: stat.mtimeMs }
434
+ const files = readdirSync(SESSIONS_DIR)
435
+ .filter((f) => f.endsWith('.jsonl'))
436
+ .map((f) => ({
437
+ name: f.replace('.jsonl', ''),
438
+ mtime: statSync(join(SESSIONS_DIR, f)).mtimeMs,
439
+ }))
440
+ .sort((a, b) => b.mtime - a.mtime)
441
+ for (const candidate of files) {
442
+ const session = SessionStore.load(candidate.name)
443
+ if (!session) continue
444
+ // Same rule as the index path: an empty session is not resumable.
445
+ if (session.metadata.messageCount === 0) continue
446
+ return {
447
+ name: candidate.name,
448
+ createdAt: session.metadata.createdAt,
449
+ updatedAt: session.metadata.updatedAt,
450
+ provider: session.metadata.provider,
451
+ model: session.metadata.model,
452
+ messageCount: session.metadata.messageCount,
453
+ tokenCount: 0,
454
+ cwd: session.metadata.cwd,
435
455
  }
436
456
  }
437
- if (!latest) return null
438
- // Load the session to extract metadata
439
- const session = SessionStore.load(latest.name)
440
- if (!session) return null
441
- return {
442
- name: latest.name,
443
- createdAt: session.metadata.createdAt,
444
- updatedAt: session.metadata.updatedAt,
445
- provider: session.metadata.provider,
446
- model: session.metadata.model,
447
- messageCount: session.metadata.messageCount,
448
- tokenCount: 0,
449
- cwd: session.metadata.cwd,
450
- }
457
+ return null
451
458
  }
452
459
 
453
460
  /**
@@ -258,9 +258,19 @@ export async function startDetachedDaemon(
258
258
  if (status) return { ok: true, pid: status.pid, port: status.port }
259
259
  if (exitCode !== null) {
260
260
  const tail = tailLog(plan.logPath)
261
+ // A denied folder is the macOS failure users hit most, and the log line
262
+ // is a bare EPERM/EACCES. Name the setting to check instead of leaving
263
+ // them to guess which sandbox refused (CC 2.1.333-158).
264
+ const privacyHint =
265
+ process.platform === 'darwin' &&
266
+ /eacces|eperm|operation not permitted|permission denied/i.test(tail)
267
+ ? '\nOn macOS this can mean the daemon may not read the project folder — check ' +
268
+ 'System Settings → Privacy & Security → Files and Folders (or Full Disk Access) ' +
269
+ 'for your terminal.'
270
+ : ''
261
271
  return {
262
272
  ok: false,
263
- reason: `daemon exited with code ${exitCode}${tail ? `:\n${tail}` : ''}`,
273
+ reason: `daemon exited with code ${exitCode}${tail ? `:\n${tail}` : ''}${privacyHint}`,
264
274
  }
265
275
  }
266
276
  }
@@ -496,6 +496,7 @@
496
496
  "location": "Location: {path}",
497
497
  "source_user": "user",
498
498
  "source_project": "project",
499
+ "source_plugin": "plugin",
499
500
  "gated": "⚠️ workspace not trusted — will not run",
500
501
  "undispatched": "⚠️ no dispatch point in this version — will not run",
501
502
  "disabled_all": "⚠️ disableAllHooks is set — will not run",
@@ -795,7 +796,10 @@
795
796
  "select_provider_hint": "Select a provider → Enter to see models",
796
797
  "select_model_hint": "Select a model → Enter to switch",
797
798
  "needs_api_key": "{provider} requires an API Key",
798
- "api_key_placeholder": "Paste API Key and press Enter..."
799
+ "api_key_placeholder": "Paste API Key and press Enter...",
800
+ "search_placeholder": "Type to filter...",
801
+ "search_no_match": "(no matching models)",
802
+ "search_hint": "Type to filter · ↑↓ move · Enter select · Esc clears search"
799
803
  },
800
804
  "command_picker": {
801
805
  "title": "Commands",
@@ -496,6 +496,7 @@
496
496
  "location": "位置: {path}",
497
497
  "source_user": "用户级",
498
498
  "source_project": "项目级",
499
+ "source_plugin": "插件",
499
500
  "gated": "⚠️ 工作区未受信任,不会运行",
500
501
  "undispatched": "⚠️ 本版本没有派发点,不会运行",
501
502
  "disabled_all": "⚠️ 已设 disableAllHooks,不会运行",
@@ -795,7 +796,10 @@
795
796
  "select_provider_hint": "选择提供商 → Enter 查看模型",
796
797
  "select_model_hint": "选择模型 → Enter 切换",
797
798
  "needs_api_key": "{provider} 需要 API Key",
798
- "api_key_placeholder": "粘贴 API Key 后按 Enter..."
799
+ "api_key_placeholder": "粘贴 API Key 后按 Enter...",
800
+ "search_placeholder": "输入以筛选...",
801
+ "search_no_match": "(无匹配模型)",
802
+ "search_hint": "输入筛选 · ↑↓ 移动 · Enter 选择 · Esc 清空搜索"
799
803
  },
800
804
  "command_picker": {
801
805
  "title": "命令",
package/src/index.tsx CHANGED
@@ -11,7 +11,9 @@ import {
11
11
  loadCrossSessionConfig,
12
12
  loadSettingsJson,
13
13
  settingsPathFor,
14
+ loadDisabledMcpServers,
14
15
  } from './config/loader'
16
+ import { getPreference } from './config/preferences'
15
17
  import {
16
18
  registerActiveSession,
17
19
  heartbeatSession,
@@ -253,6 +255,7 @@ interface SetupGateProps {
253
255
  version?: string
254
256
  sessionId: string
255
257
  agentViewManager?: AgentViewManager
258
+ reloadPlugins?: () => { plugins: number; skills: number }
256
259
  locale: string
257
260
  t: (key: string) => string
258
261
  }
@@ -300,6 +303,7 @@ function SetupGate(props: SetupGateProps) {
300
303
  version: props.version,
301
304
  sessionId: props.sessionId,
302
305
  agentViewManager: props.agentViewManager,
306
+ reloadPlugins: props.reloadPlugins,
303
307
  })
304
308
  }
305
309
 
@@ -312,7 +316,13 @@ async function connectMcpServers(
312
316
  mcpServers: McpServerConfig[],
313
317
  tools: ReturnType<typeof createToolRegistry>,
314
318
  ): Promise<McpConnectFailure[]> {
315
- if (mcpServers.length === 0) return []
319
+ // `/mcp disable` is a gate on *starting* a server, not just on its tools:
320
+ // disabled entries are filtered before any process is spawned. The filter
321
+ // lives here (the single startup path) so a future caller cannot connect a
322
+ // disabled server by forgetting a check of its own.
323
+ const disabled = loadDisabledMcpServers()
324
+ const activeServers = mcpServers.filter((s) => !disabled.has(s.name))
325
+ if (activeServers.length === 0) return []
316
326
  const mcp = McpClient.getInstance()
317
327
  // A server that dies mid-session should come back on its own; the retry is
318
328
  // bounded and stops early on a definitive refusal. `MIPHAM_MCP_AUTO_RECONNECT=0`
@@ -321,7 +331,7 @@ async function connectMcpServers(
321
331
  // Wire runtime tool-list changes before connect so mid-connect updates land.
322
332
  syncMcpToolsOnChange(mcp, tools)
323
333
  const results = await Promise.allSettled(
324
- mcpServers.map(async (server) => {
334
+ activeServers.map(async (server) => {
325
335
  await mcp.connect(server)
326
336
  registerMcpServerTools(server.name, tools)
327
337
  }),
@@ -330,7 +340,7 @@ async function connectMcpServers(
330
340
  for (let i = 0; i < results.length; i++) {
331
341
  const result = results[i]!
332
342
  if (result.status === 'rejected') {
333
- const name = mcpServers[i]!.name
343
+ const name = activeServers[i]!.name
334
344
  const reason = String(result.reason)
335
345
  failures.push({ name, reason })
336
346
  // Say the retry out loud when there is one: the client is already trying
@@ -837,6 +847,13 @@ export async function runApp(options: RunOptions): Promise<void> {
837
847
  // Create query engine
838
848
  const ruleEngine = new ExperienceRuleEngine()
839
849
  const engine = new QueryEngine(registry, context, tools, permission, ruleEngine)
850
+
851
+ // `/autocompact` persists a user override; apply it before the first turn.
852
+ const savedAutocompact = Number.parseFloat(getPreference('autocompactThreshold', ''))
853
+ if (Number.isFinite(savedAutocompact) && savedAutocompact >= 0.5 && savedAutocompact <= 0.95) {
854
+ engine.getContext().setCompactionThresholdOverride(savedAutocompact)
855
+ }
856
+
840
857
  engine.setHookEngine(hookEngine)
841
858
  engine.setArtifactServer(artifactServer)
842
859
  engine.setAgentViewManager(agentViewManager)
@@ -939,6 +956,31 @@ export async function runApp(options: RunOptions): Promise<void> {
939
956
  )
940
957
  }
941
958
 
959
+ // `/reload-plugins` re-runs the same load path. `loadPlugins` has no internal
960
+ // gate, so it must stay unreachable under `--safe-mode` (which skips plugin
961
+ // loading entirely) and under `disableAllHooks` (which exists to keep plugin
962
+ // hooks out): re-running it there would register what the operator turned off.
963
+ const reloadPlugins =
964
+ safeMode || settingsJson.disableAllHooks
965
+ ? undefined
966
+ : () => {
967
+ for (const plugin of pluginManager.list()) {
968
+ hookEngine.unregisterSource(plugin.name)
969
+ }
970
+ loadPlugins(
971
+ pluginManager,
972
+ agentRegistry,
973
+ skillsLoader,
974
+ hookEngine,
975
+ McpClient.getInstance(),
976
+ tools,
977
+ )
978
+ return {
979
+ plugins: pluginManager.getEnabled().length,
980
+ skills: skillsLoader.countByType().total,
981
+ }
982
+ }
983
+
942
984
  engine.setupContextSummarizer()
943
985
 
944
986
  // ── Cross-session messaging: register session, heartbeat, shutdown ──
@@ -1125,6 +1167,7 @@ export async function runApp(options: RunOptions): Promise<void> {
1125
1167
  version: options.version,
1126
1168
  sessionId: sessionName,
1127
1169
  agentViewManager,
1170
+ reloadPlugins,
1128
1171
  locale,
1129
1172
  t,
1130
1173
  }),
@@ -35,6 +35,30 @@ export const DEFAULT_REQUEST_TIMEOUT_MS = 60_000
35
35
  */
36
36
  export const MCP_SHUTDOWN_GRACE_MS = 300
37
37
 
38
+ /**
39
+ * Cap on one un-terminated stdio line. A server that keeps writing without a
40
+ * newline — a log line, or output without JSON-RPC framing — would otherwise
41
+ * grow `buffer` without bound for as long as the session runs (CC 2.1.333-085).
42
+ */
43
+ export const MAX_STDIO_LINE_CHARS = 8 * 1024 * 1024
44
+
45
+ /** Split a stdio chunk into complete lines, dropping an oversized partial line. */
46
+ export function takeStdioLines(
47
+ buffer: string,
48
+ chunk: string,
49
+ max = MAX_STDIO_LINE_CHARS,
50
+ ): { lines: string[]; rest: string; overflow: boolean } {
51
+ const combined = buffer + chunk
52
+ const lines = combined.split('\n')
53
+ let rest = lines.pop() || ''
54
+ let overflow = false
55
+ if (rest.length > max) {
56
+ rest = ''
57
+ overflow = true
58
+ }
59
+ return { lines, rest, overflow }
60
+ }
61
+
38
62
  /** Resolve when `proc` exits, or after `ms` — whichever comes first. */
39
63
  function waitForExit(proc: ChildProcess, ms: number): Promise<void> {
40
64
  if (proc.exitCode !== null || proc.signalCode !== null) return Promise.resolve()
@@ -224,6 +248,7 @@ export class StdioTransport implements Transport {
224
248
  >()
225
249
  private notificationHandlers: NotificationHandler[] = []
226
250
  private buffer = ''
251
+ private oversizeWarned = false
227
252
  private closed = false
228
253
 
229
254
  async start(command: string, args: string[], env?: Record<string, string>): Promise<void> {
@@ -243,9 +268,16 @@ export class StdioTransport implements Transport {
243
268
  })
244
269
 
245
270
  child.stdout?.on('data', (data: Buffer) => {
246
- this.buffer += data.toString()
247
- const lines = this.buffer.split('\n')
248
- this.buffer = lines.pop() || ''
271
+ const chunk = takeStdioLines(this.buffer, data.toString())
272
+ this.buffer = chunk.rest
273
+ if (chunk.overflow && !this.oversizeWarned) {
274
+ this.oversizeWarned = true
275
+ process.stderr.write(
276
+ `[mcp] dropped a stdio message longer than ${MAX_STDIO_LINE_CHARS} characters ` +
277
+ 'without a newline\n',
278
+ )
279
+ }
280
+ const lines = chunk.lines
249
281
 
250
282
  for (const line of lines) {
251
283
  const trimmed = line.trim()
@@ -352,7 +352,23 @@ export class AnthropicProvider implements ProviderInstance {
352
352
 
353
353
  let parsedInput: Record<string, unknown> = {}
354
354
  try {
355
- parsedInput = accumulatedToolInput ? JSON.parse(accumulatedToolInput) : {}
355
+ const parsed: unknown = accumulatedToolInput
356
+ ? JSON.parse(accumulatedToolInput)
357
+ : {}
358
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
359
+ parsedInput = parsed as Record<string, unknown>
360
+ } else {
361
+ // `null`, a number, a string or an array is not a tool
362
+ // input. Storing it verbatim poisoned the session: every
363
+ // later request re-serialized it as this call's
364
+ // `arguments` (CC 2.1.334-017).
365
+ parsedInput = {
366
+ _parseError:
367
+ `tool input must be a JSON object; received ` +
368
+ `${JSON.stringify(parsed)?.slice(0, 80) ?? String(parsed)}`,
369
+ _raw: accumulatedToolInput,
370
+ }
371
+ }
356
372
  } catch (err) {
357
373
  // Same tag as the OpenAI-compatible path: a bare fragment
358
374
  // reaches the validator as "missing required parameter",
@@ -549,7 +549,19 @@ export class OpenAICompatProvider implements ProviderInstance {
549
549
  private safeParseJson(raw: string): Record<string, unknown> {
550
550
  if (!raw) return {}
551
551
  try {
552
- return JSON.parse(raw)
552
+ const parsed: unknown = JSON.parse(raw)
553
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
554
+ return parsed as Record<string, unknown>
555
+ }
556
+ // A non-object (`null`, `5`, `"x"`, `[]`) must not reach history: it is
557
+ // re-serialized as this call's `arguments` on every later request and
558
+ // poisons the session (CC 2.1.334-017).
559
+ return {
560
+ _parseError:
561
+ `tool input must be a JSON object; received ` +
562
+ `${JSON.stringify(parsed)?.slice(0, 80) ?? String(parsed)}`,
563
+ _raw: raw,
564
+ }
553
565
  } catch (err) {
554
566
  // Tag the failure instead of handing back a bare fragment: the tool's
555
567
  // validator would then report "missing required parameter", and the model
@@ -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.52' as const
12
+ export const PACKAGE_VERSION = '0.85.54' 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 = 141 as const
78
+ export const SLASH_COMMAND_COUNT = 150 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 = 5449 as const
93
+ export const TEST_COUNT = 5540 as const