@miphamai/cli 0.85.57 → 0.85.58

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.57
1
+ # Mipham Code v0.85.58
2
2
 
3
3
  **Multi-model open-core intelligent coding terminal** — 12 AI providers, 150 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.57",
3
+ "version": "0.85.58",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
package/src/index.tsx CHANGED
@@ -51,7 +51,7 @@ import { mountSkills, SKILLS_KEY } from './skills/seam'
51
51
  import { mountLlm, LLM_KEY } from './providers/llm'
52
52
  import { mountConstitution, createConstitution } from './core/constitution-seam'
53
53
  import { ConstitutionLoader } from './core/constitution-loader'
54
- import { McpClient, describeSlowConnect } from './mcp/client'
54
+ import { McpClient, describeNpxCacheNotice, describeSlowConnect } from './mcp/client'
55
55
  import { buildMcpInstructionsBlock } from './mcp/instructions'
56
56
  import { registerMcpServerTools, syncMcpToolsOnChange } from './mcp/registry'
57
57
  import { formatMcpConnectFailures, type McpConnectFailure } from './mcp/connect-failures'
@@ -334,6 +334,7 @@ async function connectMcpServers(
334
334
  // A package-manager launch can spend the whole budget inside npx. Say which
335
335
  // package is being resolved instead of staying silent until the timeout.
336
336
  mcp.setSlowConnectReporter((notice) => console.error(describeSlowConnect(notice)))
337
+ mcp.setNpxCacheReporter((notice) => console.error(describeNpxCacheNotice(notice)))
337
338
  // Wire runtime tool-list changes before connect so mid-connect updates land.
338
339
  syncMcpToolsOnChange(mcp, tools)
339
340
  const results = await Promise.allSettled(
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 { planServerLaunch, warmNpxCache } from './npx-resolve'
14
15
  import { basename } from 'node:path'
15
16
  import { createAwakeTimer } from '../providers/fetch-utils'
16
17
  import { createT } from '../i18n-core/t'
@@ -139,6 +140,22 @@ export function describeSlowConnect(notice: SlowConnectNotice): string {
139
140
  return `[mcp] "${notice.name}" is still starting (${elapsed} elapsed, ${budget} budget)`
140
141
  }
141
142
 
143
+ export interface NpxCacheNotice {
144
+ name: string
145
+ spec: string
146
+ kind: 'used' | 'warmed'
147
+ version?: string
148
+ }
149
+
150
+ /** One line about the npx cache: a cached launch was used, or a warm-up landed. */
151
+ export function describeNpxCacheNotice(notice: NpxCacheNotice): string {
152
+ if (notice.kind === 'used') {
153
+ const version = notice.version ? ` (${notice.version})` : ''
154
+ return `[mcp] "${notice.name}": using cached ${notice.spec}${version} — starting without npx resolution`
155
+ }
156
+ return `[mcp] "${notice.name}": cached ${notice.spec} in the npx cache; the next start uses its absolute path`
157
+ }
158
+
142
159
  /**
143
160
  * Will retrying this connect failure change the answer?
144
161
  *
@@ -240,6 +257,10 @@ export class McpClient {
240
257
  private autoReconnect = false
241
258
  /** Reports a handshake that is still running after `SLOW_CONNECT_NOTICE_MS`. */
242
259
  private slowConnectReporter?: (notice: SlowConnectNotice) => void
260
+ /** Reports an npx-cache hit or a completed warm-up. */
261
+ private npxCacheReporter?: (notice: NpxCacheNotice) => void
262
+ /** Warm-ups in flight, keyed by package spec (one per spec per process). */
263
+ private warmingNpx = new Set<string>()
243
264
  /** Servers with an auto-reconnect in flight — one at a time per name. */
244
265
  private reconnecting = new Set<string>()
245
266
  /** Set by `closeAll` so a teardown is never undone by an in-flight reconnect. */
@@ -297,6 +318,11 @@ export class McpClient {
297
318
  this.slowConnectReporter = reporter
298
319
  }
299
320
 
321
+ /** Where to report an npx-cache hit or a completed warm-up. */
322
+ setNpxCacheReporter(reporter?: (notice: NpxCacheNotice) => void): void {
323
+ this.npxCacheReporter = reporter
324
+ }
325
+
300
326
  /**
301
327
  * Obtain the credentials a server's config calls for, as transport env.
302
328
  *
@@ -557,6 +583,11 @@ export class McpClient {
557
583
  }
558
584
 
559
585
  private async connectOnce(config: McpServerConfig): Promise<void> {
586
+ // A package that is already in the npx cache can be started as
587
+ // `node <bin>`; that removes registry resolution from the handshake. A
588
+ // miss keeps the original launch and asks for a background warm-up.
589
+ const plan = planServerLaunch(config)
590
+ const launch = { name: config.name, command: plan.command, args: plan.args }
560
591
  const transport: StdioTransport | HttpTransport = config.url
561
592
  ? new HttpTransport(undefined, config.request_timeout_ms)
562
593
  : new StdioTransport(config.request_timeout_ms)
@@ -577,12 +608,12 @@ export class McpClient {
577
608
  // is what an unauthenticated request gets rejected on.
578
609
  const env = await this.envWithAuth(config)
579
610
 
580
- await this.withConnectTimeout(config, async () => {
611
+ await this.withConnectTimeout(launch, async () => {
581
612
  // Start the transport (transport-specific), then perform the handshake.
582
613
  if (transport instanceof HttpTransport) {
583
614
  await transport.start(config.url ?? '', config.headers, env)
584
615
  } else {
585
- await transport.start(config.command ?? '', config.args ?? [], env)
616
+ await transport.start(launch.command ?? '', launch.args ?? [], env)
586
617
  }
587
618
  const initResult: InitializeResult = await protocol.initialize()
588
619
 
@@ -606,9 +637,20 @@ export class McpClient {
606
637
  // landed. The `connecting` promise covers this window instead.
607
638
  connection.status = 'connected'
608
639
  })
640
+ if (plan.resolved) {
641
+ this.npxCacheReporter?.({
642
+ name: config.name,
643
+ spec: `${plan.resolved.packageName}@${plan.resolved.version}`,
644
+ kind: 'used',
645
+ version: plan.resolved.version,
646
+ })
647
+ }
609
648
  } catch (err) {
610
649
  connection.status = 'error'
611
650
  connection.error = describeMcpError(err, config.name)
651
+ // The npx child was killed with the transport; resolving the package in
652
+ // the background is what makes the *next* start skip npx entirely.
653
+ if (plan.warmSpec) this.warmNpxPackage(config.name, plan.warmSpec)
612
654
  try {
613
655
  await transport.close()
614
656
  } catch {
@@ -627,8 +669,21 @@ export class McpClient {
627
669
  * server registers no tools — never give `markIfTransportLost` a chance to
628
670
  * reconnect. The server is fine; only the clock moved.
629
671
  */
630
- private async withConnectTimeout<T>(config: McpServerConfig, fn: () => Promise<T>): Promise<T> {
631
- const timeoutMs = connectTimeoutMs(config.command)
672
+ private warmNpxPackage(name: string, spec: string): void {
673
+ if (this.warmingNpx.has(spec)) return
674
+ this.warmingNpx.add(spec)
675
+ void warmNpxCache(spec)
676
+ .then((ok) => {
677
+ if (ok) this.npxCacheReporter?.({ name, spec, kind: 'warmed' })
678
+ })
679
+ .finally(() => this.warmingNpx.delete(spec))
680
+ }
681
+
682
+ private async withConnectTimeout<T>(
683
+ launch: { name: string; command?: string; args?: string[] },
684
+ fn: () => Promise<T>,
685
+ ): Promise<T> {
686
+ const timeoutMs = connectTimeoutMs(launch.command)
632
687
  // Held in an object, not a `let`: the timer is armed inside the Promise
633
688
  // executor, and assignments made there are invisible to control-flow
634
689
  // narrowing — TS keeps the variable typed `null` and the cleanup call below
@@ -645,9 +700,9 @@ export class McpClient {
645
700
  const noticeDelay = Math.min(SLOW_CONNECT_NOTICE_MS, Math.max(1, Math.floor(timeoutMs / 3)))
646
701
  timer.notice = setTimeout(() => {
647
702
  this.slowConnectReporter?.({
648
- name: config.name,
649
- command: config.command,
650
- args: config.args ?? [],
703
+ name: launch.name,
704
+ command: launch.command,
705
+ args: launch.args ?? [],
651
706
  elapsedMs: Date.now() - startedAt,
652
707
  timeoutMs,
653
708
  })
@@ -660,7 +715,7 @@ export class McpClient {
660
715
  timer.cancel = createAwakeTimer(timeoutMs, () =>
661
716
  reject(
662
717
  new Error(
663
- describeConnectTimeout(config.name, timeoutMs, config.command, config.args ?? []),
718
+ describeConnectTimeout(launch.name, timeoutMs, launch.command, launch.args ?? []),
664
719
  ),
665
720
  ),
666
721
  )
@@ -0,0 +1,227 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
3
+ import { homedir } from 'node:os'
4
+ import { basename, join } from 'node:path'
5
+
6
+ /**
7
+ * Resolve a package-manager MCP launch to an absolute bin when the package is
8
+ * already materialised in the npx cache.
9
+ *
10
+ * The launch itself is cheap (`spawn('npx')` returns at once); the cost is npm
11
+ * asking the registry again on every start, and it lands entirely inside the
12
+ * handshake budget. Once the package is in `~/.npm/_npx`, the same server can
13
+ * be started with `node <bin>` and the budget stops paying for resolution.
14
+ *
15
+ * This module never decides the trust level of a package — the user already
16
+ * asked the package manager to run it. It only reuses what that manager has
17
+ * already materialised, and refuses to guess when the package exposes more
18
+ * than one bin.
19
+ */
20
+
21
+ const PACKAGE_MANAGER_COMMANDS = new Set(['npx', 'npm', 'pnpm', 'yarn', 'bunx'])
22
+ const SUBCOMMANDS = new Set(['exec', 'x', 'dlx', 'run', 'run-script'])
23
+ /** Package managers this module can warm through `npm exec`. */
24
+ const NPM_FAMILY = new Set(['npx', 'npm'])
25
+
26
+ export interface PackageManagerLaunch {
27
+ pm: string
28
+ spec: string
29
+ /** Arguments that belong to the server, not to the package manager. */
30
+ extraArgs: string[]
31
+ }
32
+
33
+ export function parsePackageManagerLaunch(
34
+ command: string | undefined,
35
+ args: string[] = [],
36
+ ): PackageManagerLaunch | undefined {
37
+ if (!command) return undefined
38
+ const pm = basename(command)
39
+ .replace(/\.(cmd|exe|ps1)$/i, '')
40
+ .toLowerCase()
41
+ if (!PACKAGE_MANAGER_COMMANDS.has(pm)) return undefined
42
+ let spec: string | undefined
43
+ let specIndex = -1
44
+ for (let i = 0; i < args.length; i++) {
45
+ const a = args[i]!
46
+ if (a === '--') break
47
+ if (a.startsWith('-')) continue
48
+ if (SUBCOMMANDS.has(a)) continue
49
+ spec = a
50
+ specIndex = i
51
+ break
52
+ }
53
+ if (!spec) return undefined
54
+ let extra = args.slice(specIndex + 1)
55
+ if (extra[0] === '--') extra = extra.slice(1)
56
+ return { pm, spec, extraArgs: extra }
57
+ }
58
+
59
+ export interface SplitSpec {
60
+ name: string
61
+ version?: string
62
+ }
63
+
64
+ /** `@scope/pkg@1.2.3` → name `@scope/pkg`, version `1.2.3`. */
65
+ export function splitPackageSpec(spec: string): SplitSpec {
66
+ const at = spec.lastIndexOf('@')
67
+ if (at > 0) return { name: spec.slice(0, at), version: spec.slice(at + 1) }
68
+ return { name: spec }
69
+ }
70
+
71
+ export interface NpxResolution {
72
+ packageName: string
73
+ version: string
74
+ binPath: string
75
+ }
76
+
77
+ export interface ResolveOptions {
78
+ cacheRoot?: string
79
+ }
80
+
81
+ function cacheRootOf(opts: ResolveOptions = {}): string {
82
+ return opts.cacheRoot ?? process.env.MIPHAM_NPX_CACHE_DIR ?? join(homedir(), '.npm', '_npx')
83
+ }
84
+
85
+ function pickBin(binField: unknown, packageDir: string, packageName: string): string | undefined {
86
+ let rel: string | undefined
87
+ if (typeof binField === 'string') rel = binField
88
+ else if (binField && typeof binField === 'object') {
89
+ const entries = Object.entries(binField as Record<string, string>)
90
+ if (entries.length === 1) rel = entries[0]![1]
91
+ else {
92
+ // Several bins: only accept the one named after the package (the shape
93
+ // `npx <pkg>` would run). Anything else is a guess we refuse to make.
94
+ const wanted = basename(packageName).toLowerCase()
95
+ const match = entries.filter(([k]) => k.toLowerCase() === wanted)
96
+ if (match.length === 1) rel = match[0]![1]
97
+ }
98
+ }
99
+ if (!rel) return undefined
100
+ const abs = join(packageDir, rel)
101
+ return existsSync(abs) && isNodeRunnable(abs) ? abs : undefined
102
+ }
103
+
104
+ /**
105
+ * `node <bin>` is only a valid replacement for the package manager when the
106
+ * bin is a JS script. A shell or native binary would fail under node, so the
107
+ * launch stays on npx instead of trading a timeout for a crash.
108
+ */
109
+ function isNodeRunnable(abs: string): boolean {
110
+ if (/\.[cm]?js$/i.test(abs)) return true
111
+ try {
112
+ const firstLine = readFileSync(abs).subarray(0, 128).toString('utf-8').split('\n')[0] ?? ''
113
+ return firstLine.startsWith('#!') && /\bnode\b/.test(firstLine)
114
+ } catch {
115
+ return false
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Find a cached copy of `spec` under the npx cache root. Exact versions must
121
+ * match; `@latest` and a bare name accept whatever is cached. Newest cache
122
+ * directory wins when several match.
123
+ */
124
+ export function resolveFromNpxCache(
125
+ spec: string,
126
+ opts: ResolveOptions = {},
127
+ ): NpxResolution | undefined {
128
+ const { name, version } = splitPackageSpec(spec)
129
+ const root = cacheRootOf(opts)
130
+ if (!existsSync(root)) return undefined
131
+ let best: { res: NpxResolution; mtime: number } | undefined
132
+ for (const entry of readdirSync(root)) {
133
+ const packageDir = join(root, entry, 'node_modules', name)
134
+ const manifest = join(packageDir, 'package.json')
135
+ if (!existsSync(manifest)) continue
136
+ try {
137
+ const parsed = JSON.parse(readFileSync(manifest, 'utf-8')) as {
138
+ name?: string
139
+ version?: string
140
+ bin?: unknown
141
+ }
142
+ if (parsed.name !== name) continue
143
+ if (version && version !== 'latest' && parsed.version !== version) continue
144
+ const binPath = pickBin(parsed.bin, packageDir, name)
145
+ if (!binPath) continue
146
+ const mtime = statSync(manifest).mtimeMs
147
+ if (!best || mtime > best.mtime) {
148
+ best = {
149
+ res: { packageName: name, version: parsed.version ?? 'unknown', binPath },
150
+ mtime,
151
+ }
152
+ }
153
+ } catch {
154
+ // A half-written cache entry is not a candidate; the next one may be.
155
+ }
156
+ }
157
+ return best?.res
158
+ }
159
+
160
+ export interface LaunchPlan {
161
+ command?: string
162
+ args?: string[]
163
+ /** Set when the launch was rewritten to a cached bin. */
164
+ resolved?: NpxResolution
165
+ /** Set when the launch stayed on the package manager and a warm-up is useful. */
166
+ warmSpec?: string
167
+ }
168
+
169
+ /**
170
+ * Decide how to start a stdio server. A cache hit becomes
171
+ * `node <resolved bin> <server args>`; everything else is left untouched.
172
+ */
173
+ export function planServerLaunch(
174
+ config: { command?: string; args?: string[] },
175
+ opts: ResolveOptions = {},
176
+ ): LaunchPlan {
177
+ const parsed = parsePackageManagerLaunch(config.command, config.args ?? [])
178
+ if (!parsed) return { command: config.command, args: config.args }
179
+ if (NPM_FAMILY.has(parsed.pm)) {
180
+ const resolved = resolveFromNpxCache(parsed.spec, opts)
181
+ if (resolved) {
182
+ return {
183
+ command: process.execPath,
184
+ args: [resolved.binPath, ...parsed.extraArgs],
185
+ resolved,
186
+ }
187
+ }
188
+ return { command: config.command, args: config.args, warmSpec: parsed.spec }
189
+ }
190
+ return { command: config.command, args: config.args }
191
+ }
192
+
193
+ export interface WarmOptions extends ResolveOptions {
194
+ /** Injected for tests; resolves when the package manager exits. */
195
+ exec?: (command: string, args: string[]) => Promise<unknown>
196
+ }
197
+
198
+ function defaultExec(command: string, args: string[]): Promise<unknown> {
199
+ return new Promise((resolve, reject) => {
200
+ execFile(
201
+ command,
202
+ args,
203
+ // The warm-up is deliberately patient: it runs in the background and is
204
+ // not on any handshake budget. It must not hold the CLI open either.
205
+ { timeout: 10 * 60_000, env: process.env, windowsHide: true },
206
+ (err, stdout, stderr) => {
207
+ if (err) reject(err)
208
+ else resolve({ stdout, stderr })
209
+ },
210
+ ).unref?.()
211
+ })
212
+ }
213
+
214
+ /**
215
+ * Materialise `spec` into the npx cache without starting the server: npm
216
+ * resolves the package, then runs a no-op. The answer comes from the cache
217
+ * itself, not the exit code, so a partial install is not reported as success.
218
+ */
219
+ export async function warmNpxCache(spec: string, opts: WarmOptions = {}): Promise<boolean> {
220
+ const exec = opts.exec ?? defaultExec
221
+ try {
222
+ await exec('npm', ['exec', '--yes', `--package=${spec}`, '--', 'node', '-e', 'process.exit(0)'])
223
+ } catch {
224
+ return false
225
+ }
226
+ return resolveFromNpxCache(spec, opts) !== undefined
227
+ }
@@ -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.57' as const
12
+ export const PACKAGE_VERSION = '0.85.58' 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 = 5658 as const
93
+ export const TEST_COUNT = 5675 as const