@miphamai/cli 0.85.31 → 0.85.32

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 CHANGED
@@ -1,4 +1,4 @@
1
- # Mipham Code v0.85.31
1
+ # Mipham Code v0.85.32
2
2
 
3
3
  **Multi-model open-core intelligent coding terminal** — 12 AI providers, 138 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miphamai/cli",
3
- "version": "0.85.31",
3
+ "version": "0.85.32",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
package/src/mcp/client.ts CHANGED
@@ -11,6 +11,7 @@ import { HttpTransport, McpHttpError } from './http-transport'
11
11
  import { McpProtocol } from './protocol'
12
12
  import { OAuthClient } from './oauth'
13
13
  import { TokenStore } from './token-store'
14
+ import { basename } from 'node:path'
14
15
  import { createAwakeTimer } from '../providers/fetch-utils'
15
16
  import { createT } from '../i18n-core/t'
16
17
  import enUS from '../i18n-core/locales/en-US.json'
@@ -25,16 +26,46 @@ const t = createT(bundles['en-US'] || (enUS as TranslationMap), enUS as Translat
25
26
 
26
27
  // Connect-handshake timeout: a hung MCP server should fail startup fast rather
27
28
  // than block on the per-request 60s timeout. Overridable via env for tests.
28
- const DEFAULT_CONNECT_TIMEOUT_MS = 15_000
29
+ export const DEFAULT_CONNECT_TIMEOUT_MS = 15_000
30
+
31
+ /**
32
+ * Budget for a server launched through a package manager (`npx -y <pkg>`, …).
33
+ *
34
+ * `spawn('npx')` returns immediately — the dependency download happens inside
35
+ * the child, so the whole cost lands on `initialize()` waiting for a reply. A
36
+ * cold cache measured 29.9 s here (2× the default), and the server is *working*,
37
+ * not hung: failing at 15 s throws that work away and then races a second
38
+ * install against the first.
39
+ *
40
+ * Kept under `DEFAULT_REQUEST_TIMEOUT_MS` (60 s) on purpose: past it the
41
+ * handshake dies on the request timer instead, which only changes the error
42
+ * message, not the patience.
43
+ */
44
+ export const PACKAGE_MANAGER_CONNECT_TIMEOUT_MS = 45_000
45
+
46
+ /** Commands whose startup includes package resolution, so the budget is theirs. */
47
+ const PACKAGE_MANAGER_COMMANDS = new Set(['npx', 'bunx', 'npm', 'pnpm', 'yarn'])
48
+
49
+ function isPackageManagerCommand(command: string | undefined): boolean {
50
+ if (!command) return false
51
+ // Windows resolves these as `npx.cmd`; the shape of the wait is the same.
52
+ const base = basename(command)
53
+ .replace(/\.(cmd|exe|ps1)$/i, '')
54
+ .toLowerCase()
55
+ return PACKAGE_MANAGER_COMMANDS.has(base)
56
+ }
29
57
 
30
58
  // How often a caller waiting on a handshake re-checks it. A handshake settles in
31
59
  // tens of milliseconds when it settles at all; this only bounds how long the wait
32
60
  // can overshoot the moment it actually did.
33
61
  const CONNECT_POLL_MS = 50
34
62
 
35
- function connectTimeoutMs(): number {
63
+ export function connectTimeoutMs(command?: string): number {
36
64
  const env = Number(process.env.MIPHAM_MCP_CONNECT_TIMEOUT_MS)
37
- return Number.isFinite(env) && env > 0 ? env : DEFAULT_CONNECT_TIMEOUT_MS
65
+ if (Number.isFinite(env) && env > 0) return env
66
+ return isPackageManagerCommand(command)
67
+ ? PACKAGE_MANAGER_CONNECT_TIMEOUT_MS
68
+ : DEFAULT_CONNECT_TIMEOUT_MS
38
69
  }
39
70
 
40
71
  /**
@@ -449,7 +480,7 @@ export class McpClient {
449
480
  // is what an unauthenticated request gets rejected on.
450
481
  const env = await this.envWithAuth(config)
451
482
 
452
- await this.withConnectTimeout(config.name, async () => {
483
+ await this.withConnectTimeout(config.name, config.command, async () => {
453
484
  // Start the transport (transport-specific), then perform the handshake.
454
485
  if (transport instanceof HttpTransport) {
455
486
  await transport.start(config.url ?? '', config.headers, env)
@@ -499,8 +530,12 @@ export class McpClient {
499
530
  * server registers no tools — never give `markIfTransportLost` a chance to
500
531
  * reconnect. The server is fine; only the clock moved.
501
532
  */
502
- private async withConnectTimeout<T>(name: string, fn: () => Promise<T>): Promise<T> {
503
- const timeoutMs = connectTimeoutMs()
533
+ private async withConnectTimeout<T>(
534
+ name: string,
535
+ command: string | undefined,
536
+ fn: () => Promise<T>,
537
+ ): Promise<T> {
538
+ const timeoutMs = connectTimeoutMs(command)
504
539
  // Held in an object, not a `let`: the timer is armed inside the Promise
505
540
  // executor, and assignments made there are invisible to control-flow
506
541
  // narrowing — TS keeps the variable typed `null` and the cleanup call below
@@ -1,4 +1,4 @@
1
- import { spawn, type ChildProcess } from 'node:child_process'
1
+ import { execFileSync, spawn, type ChildProcess } from 'node:child_process'
2
2
  import type { JsonRpcRequest, JsonRpcResponse, JsonRpcNotification } from './types'
3
3
 
4
4
  export type NotificationHandler = (notification: JsonRpcNotification) => void
@@ -51,13 +51,17 @@ function waitForExit(proc: ChildProcess, ms: number): Promise<void> {
51
51
  /**
52
52
  * Terminate the server **and its descendants** once the grace period expired.
53
53
  *
54
- * The tree half is Windows-only, and deliberately so: Windows gives us no
55
- * process group to signal, so `taskkill /T` is the only way to reach the
56
- * server's own children. On POSIX we do **not** spawn MCP servers detached, so
57
- * the child shares our process group and has no group of its own —
58
- * `process.kill(-pid)` would be ESRCH, and making it a group leader would let
59
- * servers outlive the CLI, a worse bug than the one being fixed. There, the
60
- * grace period above *is* the fix; killing the direct child is what we always did.
54
+ * Windows has no process group to signal, so `taskkill /T` is the only way to
55
+ * reach the server's own children. On POSIX we do **not** spawn MCP servers
56
+ * detached — the child shares our process group, so `process.kill(-pid)` is
57
+ * ESRCH — and making it a group leader would let servers outlive the CLI, a
58
+ * worse bug than the one being fixed. So the descendants are enumerated from
59
+ * `ps` instead and signalled one by one.
60
+ *
61
+ * Killing only the direct child was wrong for the shape that matters:
62
+ * `npx -y some-mcp` spawns a **wrapper**, and the server that answers JSON-RPC
63
+ * is its child. Killing the wrapper re-parents that child to init and it keeps
64
+ * running — observed as accumulating `ppid=1` `node …/_npx/…/xxx-mcp` processes.
61
65
  */
62
66
  function killProcessTree(proc: ChildProcess): void {
63
67
  const pid = proc.pid
@@ -68,6 +72,16 @@ function killProcessTree(proc: ChildProcess): void {
68
72
  } catch {
69
73
  /* fall through to the direct kill */
70
74
  }
75
+ } else {
76
+ // Deepest first, while the parent links that identified them still exist:
77
+ // once the wrapper dies its children are re-parented and unfindable.
78
+ for (const descendant of descendantPids(pid).reverse()) {
79
+ try {
80
+ process.kill(descendant)
81
+ } catch {
82
+ /* already gone */
83
+ }
84
+ }
71
85
  }
72
86
  try {
73
87
  proc.kill()
@@ -76,6 +90,39 @@ function killProcessTree(proc: ChildProcess): void {
76
90
  }
77
91
  }
78
92
 
93
+ /** Every descendant of `root`, parents before children. */
94
+ function descendantPids(root: number): number[] {
95
+ let listing: string
96
+ try {
97
+ listing = execFileSync('ps', ['-A', '-o', 'pid=,ppid='], {
98
+ encoding: 'utf-8',
99
+ timeout: 2000,
100
+ })
101
+ } catch {
102
+ return [] // No `ps`, or it timed out: fall back to the direct kill.
103
+ }
104
+
105
+ const byParent = new Map<number, number[]>()
106
+ for (const line of listing.split('\n')) {
107
+ const [pidText, ppidText] = line.trim().split(/\s+/)
108
+ const pid = Number(pidText)
109
+ const ppid = Number(ppidText)
110
+ if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue
111
+ const siblings = byParent.get(ppid)
112
+ if (siblings) siblings.push(pid)
113
+ else byParent.set(ppid, [pid])
114
+ }
115
+
116
+ const descendants: number[] = []
117
+ const queue = [...(byParent.get(root) ?? [])]
118
+ while (queue.length > 0) {
119
+ const next = queue.shift()!
120
+ descendants.push(next)
121
+ queue.push(...(byParent.get(next) ?? []))
122
+ }
123
+ return descendants
124
+ }
125
+
79
126
  /** Shared timeout error for both stdio and HTTP transports. */
80
127
  export function requestTimeoutError(method: string, ms: number): Error {
81
128
  return new Error(`MCP request timeout: ${method} (${ms}ms)`)
@@ -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.31' as const
12
+ export const PACKAGE_VERSION = '0.85.32' as const
13
13
 
14
14
  /** npm install 全局安装命令 */
15
15
  export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` 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 = 4658 as const
93
+ export const TEST_COUNT = 4662 as const