@miphamai/cli 0.85.56 → 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 +1 -1
- package/package.json +1 -1
- package/src/index.tsx +5 -1
- package/src/mcp/client.ts +159 -7
- package/src/mcp/npx-resolve.ts +227 -0
- package/src/shared/package-info.ts +2 -2
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Mipham Code v0.85.
|
|
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
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 } 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'
|
|
@@ -331,6 +331,10 @@ async function connectMcpServers(
|
|
|
331
331
|
// bounded and stops early on a definitive refusal. `MIPHAM_MCP_AUTO_RECONNECT=0`
|
|
332
332
|
// turns it off (e.g. for a scripted session that must not spawn processes).
|
|
333
333
|
mcp.setAutoReconnect(process.env.MIPHAM_MCP_AUTO_RECONNECT !== '0')
|
|
334
|
+
// A package-manager launch can spend the whole budget inside npx. Say which
|
|
335
|
+
// package is being resolved instead of staying silent until the timeout.
|
|
336
|
+
mcp.setSlowConnectReporter((notice) => console.error(describeSlowConnect(notice)))
|
|
337
|
+
mcp.setNpxCacheReporter((notice) => console.error(describeNpxCacheNotice(notice)))
|
|
334
338
|
// Wire runtime tool-list changes before connect so mid-connect updates land.
|
|
335
339
|
syncMcpToolsOnChange(mcp, tools)
|
|
336
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'
|
|
@@ -68,6 +69,93 @@ export function connectTimeoutMs(command?: string): number {
|
|
|
68
69
|
: DEFAULT_CONNECT_TIMEOUT_MS
|
|
69
70
|
}
|
|
70
71
|
|
|
72
|
+
/** How long a handshake may run before the client says what it is waiting on. */
|
|
73
|
+
export const SLOW_CONNECT_NOTICE_MS = 3_000
|
|
74
|
+
|
|
75
|
+
/** Subcommands that sit between `npm`/`pnpm` and the package word. */
|
|
76
|
+
const PACKAGE_MANAGER_SUBCOMMANDS = new Set(['exec', 'x', 'dlx', 'run', 'run-script'])
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The package a package-manager launch is resolving — the first word that is
|
|
80
|
+
* neither a flag nor a subcommand. Used only in messages; `undefined` when the
|
|
81
|
+
* args carry no package word (then the message simply omits it).
|
|
82
|
+
*/
|
|
83
|
+
export function packageSpecOf(args: string[] = []): string | undefined {
|
|
84
|
+
for (const arg of args) {
|
|
85
|
+
if (!arg || arg.startsWith('-')) continue
|
|
86
|
+
if (PACKAGE_MANAGER_SUBCOMMANDS.has(arg)) continue
|
|
87
|
+
return arg
|
|
88
|
+
}
|
|
89
|
+
return undefined
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Timeout message with the one thing the bare text cannot carry: that the
|
|
94
|
+
* budget may have been spent in package resolution, not in the server.
|
|
95
|
+
*
|
|
96
|
+
* A pinned absolute path removes that cost entirely; the env override is the
|
|
97
|
+
* escape hatch when the user wants to keep `npx`.
|
|
98
|
+
*/
|
|
99
|
+
export function describeConnectTimeout(
|
|
100
|
+
name: string,
|
|
101
|
+
timeoutMs: number,
|
|
102
|
+
command?: string,
|
|
103
|
+
args: string[] = [],
|
|
104
|
+
): string {
|
|
105
|
+
const base = `MCP connect timed out for "${name}" after ${timeoutMs}ms`
|
|
106
|
+
if (!isPackageManagerCommand(command)) return base
|
|
107
|
+
const pm = basename(command!).replace(/\.(cmd|exe|ps1)$/i, '')
|
|
108
|
+
const pkg = packageSpecOf(args)
|
|
109
|
+
const target = pkg ? ` (${pkg})` : ''
|
|
110
|
+
return (
|
|
111
|
+
`${base} — it was started via ${pm}${target}, whose package resolution runs before the ` +
|
|
112
|
+
`handshake and can exceed this budget even when the server is fine. Pin an absolute path ` +
|
|
113
|
+
`(e.g. command "node" with the server's dist entry) or raise MIPHAM_MCP_CONNECT_TIMEOUT_MS.`
|
|
114
|
+
)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export interface SlowConnectNotice {
|
|
118
|
+
name: string
|
|
119
|
+
command?: string
|
|
120
|
+
args: string[]
|
|
121
|
+
elapsedMs: number
|
|
122
|
+
timeoutMs: number
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* One line while the budget is still running: which server, which package (if a
|
|
127
|
+
* package manager is resolving one), how long so far, and how long it is
|
|
128
|
+
* allowed. Without it a 45 s npx download looks exactly like a hang, and the
|
|
129
|
+
* only message the user ever sees is the failure.
|
|
130
|
+
*/
|
|
131
|
+
export function describeSlowConnect(notice: SlowConnectNotice): string {
|
|
132
|
+
const elapsed = `${Math.max(1, Math.round(notice.elapsedMs / 1000))}s`
|
|
133
|
+
const budget = `${Math.round(notice.timeoutMs / 1000)}s`
|
|
134
|
+
if (isPackageManagerCommand(notice.command)) {
|
|
135
|
+
const pm = basename(notice.command!).replace(/\.(cmd|exe|ps1)$/i, '')
|
|
136
|
+
const pkg = packageSpecOf(notice.args)
|
|
137
|
+
const target = pkg ? ` ${pkg}` : ''
|
|
138
|
+
return `[mcp] "${notice.name}" is still starting — resolving ${pm} package${target} (${elapsed} elapsed, ${budget} budget)`
|
|
139
|
+
}
|
|
140
|
+
return `[mcp] "${notice.name}" is still starting (${elapsed} elapsed, ${budget} budget)`
|
|
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
|
+
|
|
71
159
|
/**
|
|
72
160
|
* Will retrying this connect failure change the answer?
|
|
73
161
|
*
|
|
@@ -167,6 +255,12 @@ export class McpClient {
|
|
|
167
255
|
* is only about *when* it is called — not how it behaves.
|
|
168
256
|
*/
|
|
169
257
|
private autoReconnect = false
|
|
258
|
+
/** Reports a handshake that is still running after `SLOW_CONNECT_NOTICE_MS`. */
|
|
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>()
|
|
170
264
|
/** Servers with an auto-reconnect in flight — one at a time per name. */
|
|
171
265
|
private reconnecting = new Set<string>()
|
|
172
266
|
/** Set by `closeAll` so a teardown is never undone by an in-flight reconnect. */
|
|
@@ -216,6 +310,19 @@ export class McpClient {
|
|
|
216
310
|
this.autoReconnect = enabled
|
|
217
311
|
}
|
|
218
312
|
|
|
313
|
+
/**
|
|
314
|
+
* Where to say "still starting" while a handshake is inside its budget.
|
|
315
|
+
* Installed by the CLI entry point; unset in tests and headless callers.
|
|
316
|
+
*/
|
|
317
|
+
setSlowConnectReporter(reporter?: (notice: SlowConnectNotice) => void): void {
|
|
318
|
+
this.slowConnectReporter = reporter
|
|
319
|
+
}
|
|
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
|
+
|
|
219
326
|
/**
|
|
220
327
|
* Obtain the credentials a server's config calls for, as transport env.
|
|
221
328
|
*
|
|
@@ -476,6 +583,11 @@ export class McpClient {
|
|
|
476
583
|
}
|
|
477
584
|
|
|
478
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 }
|
|
479
591
|
const transport: StdioTransport | HttpTransport = config.url
|
|
480
592
|
? new HttpTransport(undefined, config.request_timeout_ms)
|
|
481
593
|
: new StdioTransport(config.request_timeout_ms)
|
|
@@ -496,12 +608,12 @@ export class McpClient {
|
|
|
496
608
|
// is what an unauthenticated request gets rejected on.
|
|
497
609
|
const env = await this.envWithAuth(config)
|
|
498
610
|
|
|
499
|
-
await this.withConnectTimeout(
|
|
611
|
+
await this.withConnectTimeout(launch, async () => {
|
|
500
612
|
// Start the transport (transport-specific), then perform the handshake.
|
|
501
613
|
if (transport instanceof HttpTransport) {
|
|
502
614
|
await transport.start(config.url ?? '', config.headers, env)
|
|
503
615
|
} else {
|
|
504
|
-
await transport.start(
|
|
616
|
+
await transport.start(launch.command ?? '', launch.args ?? [], env)
|
|
505
617
|
}
|
|
506
618
|
const initResult: InitializeResult = await protocol.initialize()
|
|
507
619
|
|
|
@@ -525,9 +637,20 @@ export class McpClient {
|
|
|
525
637
|
// landed. The `connecting` promise covers this window instead.
|
|
526
638
|
connection.status = 'connected'
|
|
527
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
|
+
}
|
|
528
648
|
} catch (err) {
|
|
529
649
|
connection.status = 'error'
|
|
530
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)
|
|
531
654
|
try {
|
|
532
655
|
await transport.close()
|
|
533
656
|
} catch {
|
|
@@ -546,32 +669,61 @@ export class McpClient {
|
|
|
546
669
|
* server registers no tools — never give `markIfTransportLost` a chance to
|
|
547
670
|
* reconnect. The server is fine; only the clock moved.
|
|
548
671
|
*/
|
|
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
|
+
|
|
549
682
|
private async withConnectTimeout<T>(
|
|
550
|
-
name: string,
|
|
551
|
-
command: string | undefined,
|
|
683
|
+
launch: { name: string; command?: string; args?: string[] },
|
|
552
684
|
fn: () => Promise<T>,
|
|
553
685
|
): Promise<T> {
|
|
554
|
-
const timeoutMs = connectTimeoutMs(command)
|
|
686
|
+
const timeoutMs = connectTimeoutMs(launch.command)
|
|
555
687
|
// Held in an object, not a `let`: the timer is armed inside the Promise
|
|
556
688
|
// executor, and assignments made there are invisible to control-flow
|
|
557
689
|
// narrowing — TS keeps the variable typed `null` and the cleanup call below
|
|
558
690
|
// is a type error rather than code.
|
|
559
|
-
const timer: { cancel?: () => void } = {}
|
|
691
|
+
const timer: { cancel?: () => void; notice?: ReturnType<typeof setTimeout> } = {}
|
|
560
692
|
// Swallow a late rejection: if the timeout wins, transport.close() in the
|
|
561
693
|
// caller's catch makes fn()'s pending request reject after we've moved on.
|
|
562
694
|
const work = fn()
|
|
563
695
|
work.catch(() => {})
|
|
696
|
+
// Say what is being waited on while the budget is still running. The delay
|
|
697
|
+
// scales down with the budget, so a test-sized timeout still gets a notice
|
|
698
|
+
// and a 45 s npx budget is not narrowed by the progress line itself.
|
|
699
|
+
const startedAt = Date.now()
|
|
700
|
+
const noticeDelay = Math.min(SLOW_CONNECT_NOTICE_MS, Math.max(1, Math.floor(timeoutMs / 3)))
|
|
701
|
+
timer.notice = setTimeout(() => {
|
|
702
|
+
this.slowConnectReporter?.({
|
|
703
|
+
name: launch.name,
|
|
704
|
+
command: launch.command,
|
|
705
|
+
args: launch.args ?? [],
|
|
706
|
+
elapsedMs: Date.now() - startedAt,
|
|
707
|
+
timeoutMs,
|
|
708
|
+
})
|
|
709
|
+
}, noticeDelay)
|
|
710
|
+
timer.notice.unref?.()
|
|
564
711
|
try {
|
|
565
712
|
return await Promise.race([
|
|
566
713
|
work,
|
|
567
714
|
new Promise<never>((_, reject) => {
|
|
568
715
|
timer.cancel = createAwakeTimer(timeoutMs, () =>
|
|
569
|
-
reject(
|
|
716
|
+
reject(
|
|
717
|
+
new Error(
|
|
718
|
+
describeConnectTimeout(launch.name, timeoutMs, launch.command, launch.args ?? []),
|
|
719
|
+
),
|
|
720
|
+
),
|
|
570
721
|
)
|
|
571
722
|
}),
|
|
572
723
|
])
|
|
573
724
|
} finally {
|
|
574
725
|
timer.cancel?.()
|
|
726
|
+
if (timer.notice) clearTimeout(timer.notice)
|
|
575
727
|
}
|
|
576
728
|
}
|
|
577
729
|
|
|
@@ -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.
|
|
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 =
|
|
93
|
+
export const TEST_COUNT = 5675 as const
|